<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

// +----------------------------------------------------------------------
// | 商城-商品订单
// +----------------------------------------------------------------------
namespace app\controller;
use think\facade\Log;
use think\facade\View;
use think\facade\Db;
class ShopOrder extends Common
{
    public function initialize(){
        parent::initialize();
    }
	//订单列表
    public function index(){
        if(request()->isAjax()){
			$page = input('param.page');
			$limit = input('param.limit');
			if(input('param.field') && input('param.order')){
				$order = 'order.'.input('param.field').' '.input('param.order');
			}else{
				$order = 'order.id desc';
			}
			$where = [];
			$where[] = ['order.aid','=',aid];
			if(bid==0){
				if(input('param.bid')){
					$where[] = ['order.bid','=',input('param.bid')];
				}elseif(input('param.showtype')==2){
					$where[] = ['order.bid','<>',0];
				}else{
					$where[] = ['order.bid','=',0];
				}
			}else{
				$where[] = ['order.bid','=',bid];
			}
			if($this->mdid){
				$where[] = ['order.mdid','=',$this->mdid];
			}
			if(input('?param.ogid')){
				if(input('param.ogid')==''){
					$where[] = ['1','=',0];
				}else{
					$ids = Db::name('shop_order_goods')->where('id','in',input('param.ogid'))->column('orderid');
					$where[] = ['order.id','in',$ids];
				}
			}
			if(input('param.mid')){
                if(false){}else{
                    $where[] = ['order.mid','=',input('param.mid')];
                }
            } else {
                }

			if(input('param.orderid')) $where[] = ['order.id','=',input('param.orderid')];
            if(input('param.freight_id')) $where[] = ['order.freight_id','=',input('param.freight_id')];
			if(input('param.proname')) $where[] = ['order.proname','like','%'.input('param.proname').'%'];
			if(input('param.ordernum')) $where[] = ['order.ordernum','like','%'.input('param.ordernum').'%'];
            if(input('param.nickname')) $where[] = ['member.nickname|member.realname','like','%'.input('param.nickname').'%'];
            if(input('param.linkman')) $where[] = ['order.linkman|order.tel','like','%'.input('param.linkman').'%'];
			if(input('param.tel')) $where[] = ['order.tel','like','%'.input('param.tel').'%'];
			if(input('param.proid')){
				$orderids = Db::name('shop_order_goods')->where('aid',aid)->where('proid',input('param.proid'))->column('orderid');
				$where[] = ['order.id','in',$orderids];
			}
			if(input('param.ctime')){
				$ctime = explode(' ~ ',input('param.ctime'));
				if(input('param.time_type') == 1){ //下单时间
					$where[] = ['order.createtime','>=',strtotime($ctime[0])];
					$where[] = ['order.createtime','<',strtotime($ctime[1])];
				}elseif(input('param.time_type') == 2){ //付款时间
					$where[] = ['order.paytime','>=',strtotime($ctime[0])];
					$where[] = ['order.paytime','<',strtotime($ctime[1])];
				}elseif(input('param.time_type') == 3){ //发货时间
					$where[] = ['order.send_time','>=',strtotime($ctime[0])];
					$where[] = ['order.send_time','<',strtotime($ctime[1])];
				}elseif(input('param.time_type') == 4){ //完成时间
					$where[] = ['order.collect_time','>=',strtotime($ctime[0])];
					$where[] = ['order.collect_time','<',strtotime($ctime[1])];
				}
			}
			if(input('param.keyword')){
				$keyword = input('param.keyword');
				$keyword_type = input('param.keyword_type');
				if($keyword_type == 1){ //订单号
					$where[] = ['order.ordernum','like','%'.$keyword.'%'];
				}elseif($keyword_type == 2){ //会员ID
					$where[] = ['order.mid','=',$keyword];
				}elseif($keyword_type == 3){ //会员信息
					$where[] = ['member.nickname|member.realname','like','%'.$keyword.'%'];
				}elseif($keyword_type == 4){ //收货信息
					$where[] = ['order.linkman|order.tel|order.area|order.address','like','%'.$keyword.'%'];
				}elseif($keyword_type == 5){ //快递单号
					$where[] = ['order.express_no','like','%'.$keyword.'%'];
				}elseif($keyword_type == 6){ //商品ID
					$orderids = Db::name('shop_order_goods')->where('aid',aid)->where('proid',$keyword)->column('orderid');
					$where[] = ['order.id','in',$orderids];
				}elseif($keyword_type == 7){ //商品名称
					$orderids = Db::name('shop_order_goods')->where('aid',aid)->where('name','like','%'.$keyword.'%')->column('orderid');
					$where[] = ['order.id','in',$orderids];
				}elseif($keyword_type == 8){ //商品编码
					$orderids = Db::name('shop_order_goods')->where('aid',aid)->where('procode','like','%'.$keyword.'%')->column('orderid');
					$where[] = ['order.id','in',$orderids];
				}elseif($keyword_type == 9){ //核销员
					$orderids = Db::name('hexiao_order')->where('aid',aid)->where('type','shop')->where('remark','like','%'.$keyword.'%')->column('orderid');
					$where[] = ['order.id','in',$orderids];
				}elseif($keyword_type == 10){ //所属门店
					$mdids = Db::name('mendian')->where('aid',aid)->where('name','like','%'.$keyword.'%')->column('id');
					$where[] = ['order.mdid','in',$mdids];
				}
			}
			if(input('?param.transfer_check') && input('param.transfer_check')!==''){
				$where[] = ['order.paytypeid','=',5];
				$where[] = ['order.transfer_check','=',input('param.transfer_check')];
			}
			if(input('?param.status') && input('param.status')!==''){
				if(input('param.status') == 5){
					$where[] = ['order.refund_status','=',1];
				}elseif(input('param.status') == 6){
					$where[] = ['order.refund_status','=',2];
				}elseif(input('param.status') == 7){
					$where[] = ['order.refund_status','=',3];
				}elseif(input('param.status') == 22){
					$where[] = ['order.status','=',2];
					$where[] = ['order.express_isbufen','=',1];
				}else{
					$where[] = ['order.status','=',input('param.status')];
				}
			}
			$totalcommission = 0;
			if(input('param.fxmid')){
				$fxmid = input('param.fxmid/d');
				if($page == 1){
					$where1 = $where;
					$where1[] = Db::raw("order.id in (select orderid from ".table_name('shop_order_goods')." where parent1={$fxmid})");
					$totalcommission1 = Db::name('shop_order_goods')->where('orderid','in',function($query)use($where1){
						$query->name('shop_order')->alias('order')->leftJoin('member member','member.id=order.mid')->where($where1)->field('order.id');
					})->sum('parent1commission');
					$where2 = $where;
					$where2[] = Db::raw("order.id in (select orderid from ".table_name('shop_order_goods')." where parent2={$fxmid})");
					$totalcommission2 = Db::name('shop_order_goods')->where('orderid','in',function($query)use($where2){
						$query->name('shop_order')->alias('order')->leftJoin('member member','member.id=order.mid')->where($where2)->field('order.id');
					})->sum('parent2commission');
					$where3 = $where;
					$where3[] = Db::raw("order.id in (select orderid from ".table_name('shop_order_goods')." where parent3={$fxmid})");
					$totalcommission3 = Db::name('shop_order_goods')->where('orderid','in',function($query)use($where3){
						$query->name('shop_order')->alias('order')->leftJoin('member member','member.id=order.mid')->where($where3)->field('order.id');
					})->sum('parent3commission');

					$totalcommission = round($totalcommission1 + $totalcommission2 + $totalcommission3,2);
				}

				$where[] = Db::raw("order.id in (select orderid from ".table_name('shop_order_goods')." where parent1={$fxmid} or parent2={$fxmid} or parent3={$fxmid})");
			}
			$count = 0 + Db::name('shop_order')->alias('order')->leftJoin('member member','member.id=order.mid')->where($where)->count();
			//echo M()->_sql();
			$list = Db::name('shop_order')->alias('order')->field('order.*')->leftJoin('member member','member.id=order.mid')->where($where)->page($page,$limit)->order($order)->select()->toArray();

			foreach($list as $k=>$vo){
				$member = Db::name('member')->where('id',$vo['mid'])->find();
				$oglist = Db::name('shop_order_goods')->where('aid',aid)->where('orderid',$vo['id'])->select()->toArray();
				$goodsdata=array();
				foreach($oglist as $og){
				    $grstr = '';
				    $goodshtml = '<div style="font-size:12px;float:left;clear:both;margin:1px 0">'.
						'<img src="'.$og['pic'].'" style="max-width:60px;float:left">'.
						'<div style="float: left;width:180px;margin-left: 10px;white-space:normal;line-height:16px;">'.
							'<div style="width:100%;min-height:25px;max-height:32px;overflow:hidden">'.$og['name'].'</div>'.
							'<div style="padding-top:0px;color:#f60"><span style="color:#888">'.$og['ggname'].'</span></div>'.$grstr.
							'<div style="padding-top:0px;color:#f60;">￥'.$og['sell_price'].' × '.$og['num'].'</div>'.
						'</div>'.
					'</div>';
                    $goodsdata[] = $goodshtml;
				}
				$list[$k]['goodsdata'] = implode('',$goodsdata);
				if($vo['bid'] > 0){
					$list[$k]['bname'] = Db::name('business')->where('aid',aid)->where('id',$vo['bid'])->value('name');
				}else{
					$list[$k]['bname'] = '平台自营';
				}
                $refundOrder = Db::name('shop_refund_order')->where('refund_status','>',0)->where('aid',aid)->where('orderid',$vo['id'])->count();
                $list[$k]['refundCount'] = $refundOrder;
                $list[$k]['payorder'] = [];
                if($vo['paytypeid'] == 5) {
                    $list[$k]['payorder'] = Db::name('payorder')->where('id',$vo['payorderid'])->where('aid',aid)->find();
                }
				$list[$k]['nickname'] = $member['nickname'];
				$list[$k]['headimg'] = $member['headimg'];
				$list[$k]['m_remark'] = $member['remark'];
				$list[$k]['platform'] = getplatformname($vo['platform']);
				if($order_show_member_apply) {
                    $member_level = Db::name('member_level')->where('id',$member['levelid'])->find();
                    $list[$k]['member_apply_info'] = $member['realname'] . '<br>'.$member['tel'] .'<br>'. $member_level['name'];
                }
			}
			return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$list,'totalcommission'=>$totalcommission]);
		}
		$machinelist = Db::name('wifiprint_set')->where('aid',aid)->where('status',1)->where('bid',bid)->select()->toArray();
		$hasprint = 0;
		if($machinelist){
			$hasprint = 1;
		}
		$peisong_set = Db::name('peisong_set')->where('aid',aid)->find();
		if($peisong_set['status']==1 && bid>0 && $peisong_set['businessst']==0 && $peisong_set['make_status']==0) $peisong_set['status'] = 0;
        $freight = Db::name('freight')->where('aid',aid)->where('bid',bid)->select()->toArray();
		
		$adminset = Db::name('admin_set')->where('aid',aid)->find();
        View::assign('freight',$freight);
		View::assign('peisong_set',$peisong_set);
		View::assign('hasprint',$hasprint);
		View::assign('express_data',express_data());
		View::assign('adminset',$adminset);
		return View::fetch();
    }
	//导出
	public function excel(){
		set_time_limit(0);
		ini_set('memory_limit', '2000M');
		if(input('param.field') && input('param.order')){
			$order = input('param.field').' '.input('param.order');
		}else{
			$order = 'id desc';
		}
		$where = [];
		$where[] = ['order.aid','=',aid];
		if(bid==0){
			if(input('param.bid')){
				$where[] = ['order.bid','=',input('param.bid')];
			}elseif(input('param.showtype')==2){
				$where[] = ['order.bid','<>',0];
			}else{
				$where[] = ['order.bid','=',0];
			}
		}else{
			$where[] = ['order.bid','=',bid];
		}
		if($this->mdid){
			$where[] = ['order.mdid','=',$this->mdid];
		}
		if(input('param.mid')) $where[] = ['order.mid','=',input('param.mid')];
		if(input('param.proname')) $where[] = ['order.proname','like','%'.input('param.proname').'%'];
		if(input('param.ordernum')) $where[] = ['order.ordernum','like','%'.input('param.ordernum').'%'];
        if(input('param.nickname')) $where[] = ['member.nickname|member.realname','like','%'.input('param.nickname').'%'];
        if(input('param.linkman')) $where[] = ['order.linkman','like','%'.input('param.linkman').'%'];
		if(input('param.tel')) $where[] = ['order.tel','like','%'.input('param.tel').'%'];
		if(input('?param.transfer_check') && input('param.transfer_check')!==''){
			$where[] = ['order.paytypeid','=',5];
			$where[] = ['order.transfer_check','=',input('param.transfer_check')];
		}
		if(input('?param.status') && input('param.status')!==''){
			if(input('param.status') == 5){
				$where[] = ['order.refund_status','=',1];
			}elseif(input('param.status') == 6){
				$where[] = ['order.refund_status','=',2];
			}elseif(input('param.status') == 7){
				$where[] = ['order.refund_status','=',3];
			}else{
				$where[] = ['order.status','=',input('param.status')];
			}
		}
		if(input('param.ctime')){
			$ctime = explode(' ~ ',input('param.ctime'));
			if(input('param.time_type') == 1){ //下单时间
				$where[] = ['order.createtime','>=',strtotime($ctime[0])];
				$where[] = ['order.createtime','<',strtotime($ctime[1]) + 86400];
			}elseif(input('param.time_type') == 2){ //付款时间
				$where[] = ['order.paytime','>=',strtotime($ctime[0])];
				$where[] = ['order.paytime','<',strtotime($ctime[1]) + 86400];
			}elseif(input('param.time_type') == 3){ //发货时间
				$where[] = ['order.send_time','>=',strtotime($ctime[0])];
				$where[] = ['order.send_time','<',strtotime($ctime[1]) + 86400];
			}elseif(input('param.time_type') == 4){ //完成时间
				$where[] = ['order.collect_time','>=',strtotime($ctime[0])];
				$where[] = ['order.collect_time','<',strtotime($ctime[1]) + 86400];
			}
		}
		if(input('param.keyword')){
			$keyword = input('param.keyword');
			$keyword_type = input('param.keyword_type');
			if($keyword_type == 1){ //订单号
				$where[] = ['order.ordernum','like','%'.$keyword.'%'];
			}elseif($keyword_type == 2){ //会员ID
				$where[] = ['order.mid','=',$keyword];
			}elseif($keyword_type == 3){ //会员信息
				$where[] = ['member.nickname|member.realname','like','%'.$keyword.'%'];
			}elseif($keyword_type == 4){ //收货信息
				$where[] = ['order.linkman|order.tel|order.area|order.address','like','%'.$keyword.'%'];
			}elseif($keyword_type == 5){ //快递单号
				$where[] = ['order.express_no','like','%'.$keyword.'%'];
			}elseif($keyword_type == 6){ //商品ID
				$orderids = Db::name('shop_order_goods')->where('aid',aid)->where('proid',$keyword)->column('orderid');
				$where[] = ['order.id','in',$orderids];
			}elseif($keyword_type == 7){ //商品名称
				$orderids = Db::name('shop_order_goods')->where('aid',aid)->where('name','like','%'.$keyword.'%')->column('orderid');
				$where[] = ['order.id','in',$orderids];
			}elseif($keyword_type == 8){ //商品编码
				$orderids = Db::name('shop_order_goods')->where('aid',aid)->where('procode','like','%'.$keyword.'%')->column('orderid');
				$where[] = ['order.id','in',$orderids];
			}elseif($keyword_type == 9){ //核销员
				$orderids = Db::name('hexiao_order')->where('aid',aid)->where('type','shop')->where('remark','like','%'.$keyword.'%')->column('orderid');
				$where[] = ['order.id','in',$orderids];
			}elseif($keyword_type == 10){ //所属门店
				$mdids = Db::name('mendian')->where('aid',aid)->where('name','like','%'.$keyword.'%')->column('id');
				$where[] = ['order.mdid','in',$mdids];
			}
		}
		
		if(input('param.fxmid')){
			$fxmid = input('param.fxmid/d');
			$where[] = Db::raw("order.id in (select orderid from ".table_name('shop_order_goods')." where parent1={$fxmid} or parent2={$fxmid} or parent3={$fxmid})");
		}

		$list = Db::name('shop_order')->alias('order')->field('order.*')->leftJoin('member member','member.id=order.mid')->where($where)->order($order)->select()->toArray();
		if(false){}else{
			$bArr = Db::name('business')->where('aid',aid)->column('name','id');
			if(!$bArr) $bArr = [];
			$bArr['0'] = '自营';
			$title = array('订单号','openid','来源','所属商家','下单人','姓名','电话','收货地址','商品名称','商品编码','规格','数量','总价','单价','成本','折扣金额','实付款','支付方式','配送方式','卡密','配送/提货时间','运费','积分抵扣','满额立减','优惠券优惠','状态','下单时间','付款时间','发货时间','完成时间','快递信息','表单信息','商家备注','核销员','核销门店','佣金总额','一级佣金','会员信息','二级佣金','会员信息','三级佣金','会员信息');
			$data = [];
			foreach($list as $k=>$vo){
				
				$status='';
				if($vo['status']==0){
					$status = '未支付';
				}elseif($vo['status']==2){
					$status = '已发货';
				}elseif($vo['status']==1){
					$status = '已支付';
				}elseif($vo['status']==3){
					$status = '已收货';
				}elseif($vo['status']==4){
					$status = '已关闭';
				}
				$member = Db::name('member')->where('id',$vo['mid'])->find();
				$oglist = Db::name('shop_order_goods')->where('orderid',$vo['id'])->select()->toArray();
				//$xm=array();
				foreach($oglist as $k2=>$og){
				    $barcode = '';
				    if($og['barcode'])  $barcode = "(".$og['barcode'].")";
					//$xm[] = $og['name'].$barcode."/".$og['ggname']." × ".$og['num']."";
					
					$parent1commission = $og['parent1'] ? $og['parent1commission'] : 0;
					$parent2commission = $og['parent2'] ? $og['parent2commission'] : 0;
					$parent3commission = $og['parent3'] ? $og['parent3commission'] : 0;
					$totalcommission = $parent1commission+$parent2commission+$parent3commission;
					if($og['parent1']){
						$parent1 = Db::name('member')->where('id',$og['parent1'])->find();
						$parent1str = $parent1['nickname'].'(会员ID:'.$parent1['id'].')';
					}else{
						$parent1str = '';
					}
					if($og['parent2']){
						$parent2 = Db::name('member')->where('id',$og['parent2'])->find();
						$parent2str = $parent2['nickname'].'(会员ID:'.$parent2['id'].')';
					}else{
						$parent2str = '';
					}
					if($og['parent3']){
						$parent3 = Db::name('member')->where('id',$og['parent3'])->find();
						$parent3str = $parent3['nickname'].'(会员ID:'.$parent3['id'].')';
					}else{
						$parent3str = '';
					}
					//配送自定义表单
					$vo['formdata'] = \app\model\Freight::getformdata($vo['id'],'shop_order');
					$formdataArr = [];
					$message = '';
					if($vo['formdata']) {
						foreach ($vo['formdata'] as $formdata) {
							if($formdata[2] != 'upload') {
								//if($formdata[0] == '备注') {
								//	$message = $formdata[1];
								//} else {
									$formdataArr[] = $formdata[0].':'.$formdata[1];
								//}
							}
						}
					}
					$formdatastr = implode("\r\n",$formdataArr);

					if($vo['freight_type'] == 1 && $vo['status'] == 3){
						$hexiao_order = Db::name('hexiao_order')->where('aid',aid)->where('orderid',$vo['id'])->where('type','shop')->find();
						if($hexiao_order){
							$hexiao_order['uname'] = Db::name('admin_user')->where('id',$hexiao_order['uid'])->value('un');
							$hexiao_order['mendian'] = Db::name('mendian')->where('id',$vo['mdid'])->value('name');
						}
					}
					$paytype = $vo['paytype'];
					if($k2 == 0){
						$data[] = [
							' '.$vo['ordernum'],
							$member[$vo['platform'].'openid'],
							getplatformname($vo['platform']),
							$bArr[$vo['bid']],
							$member['nickname'],
							$vo['linkman'],
							$vo['tel'],
							$vo['area'].' '.$vo['address'],
							$og['name'],
							$og['procode'],
							$og['ggname'].$barcode,
							$og['num'],
							$og['totalprice'],
							$og['sell_price'],
							$og['cost_price'],
							$vo['leveldk_money'],
							$vo['totalprice'],
							$paytype,
							$vo['freight_text'],
							' '.$vo['freight_content'],
							$vo['freight_time'],
							$vo['freight_price'],
							$vo['scoredk_money'],
							$vo['manjian_money'],
							$vo['coupon_money'],
							$status,
							date('Y-m-d H:i:s',$vo['createtime']),
							$vo['paytime'] ? date('Y-m-d H:i:s',$vo['paytime']) : '',
							$vo['send_time'] ? date('Y-m-d H:i:s',$vo['send_time']) : '',
							$vo['collect_time'] ? date('Y-m-d H:i:s',$vo['collect_time']) : '',
							($vo['express_com'] ? $vo['express_com'].'('.$vo['express_no'].')':''),
							$formdatastr,
							$vo['remark'],
							$hexiao_order['uname'],
							$hexiao_order['mendian'],
							$totalcommission,
							$parent1commission,
							$parent1str,
							$parent2commission,
							$parent2str,
							$parent3commission,
							$parent3str,
						];
					}else{
						$data[] = [
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							$og['name'],
                            $og['procode'],
							$og['ggname'].$barcode,
							$og['num'],
							$og['totalprice'],
							$og['sell_price'],
							$og['cost_price'],
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							'',
							$totalcommission,
							$parent1commission,
							$parent1str,
							$parent2commission,
							$parent2str,
							$parent3commission,
							$parent3str,
						];
					}

				}
			}
			$this->export_excel($title,$data);
		}
	}
	//订单详情
	public function getdetail(){
		$orderid = input('param.orderid');
		if(bid != 0){
			$order = Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('id',$orderid)->find();
		}else{
			$order = Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->find();
		}
        $order['school_info'] = '';
		if($order['coupon_rid']){
			$couponrecord = Db::name('coupon_record')->where('id',$order['coupon_rid'])->find();
			$couponnames = Db::name('coupon_record')->where('id','in',$order['coupon_rid'])->column('couponname');
			$couponnames = implode('，',$couponnames);
		}else{
			$couponrecord = false;
			$couponnames = '';
		}
		$oglist = Db::name('shop_order_goods')->where('aid',aid)->where('orderid',$orderid)->select()->toArray();
		$member = Db::name('member')->field('id,nickname,headimg,realname,tel,wxopenid,unionid')->where('id',$order['mid'])->find();
		if(!$member) $member = ['id'=>$order['mid'],'nickname'=>'','headimg'=>''];
		$comdata = array();
		$comdata['parent1'] = ['mid'=>'','nickname'=>'','headimg'=>'','money'=>0,'score'=>0];
		$comdata['parent2'] = ['mid'=>'','nickname'=>'','headimg'=>'','money'=>0,'score'=>0];
		$comdata['parent3'] = ['mid'=>'','nickname'=>'','headimg'=>'','money'=>0,'score'=>0];
		$ogids = [];
		foreach($oglist as $gk=>$v){
			$ogids[] = $v['id'];
			if($v['parent1']){
				$parent1 = Db::name('member')->where('id',$v['parent1'])->find();
				$comdata['parent1']['mid'] = $v['parent1'];
				$comdata['parent1']['nickname'] = $parent1['nickname'];
				$comdata['parent1']['headimg'] = $parent1['headimg'];
				$comdata['parent1']['money'] += $v['parent1commission'];
				$comdata['parent1']['score'] += $v['parent1score'];
			}
			if($v['parent2']){
				$parent2 = Db::name('member')->where('id',$v['parent2'])->find();
				$comdata['parent2']['mid'] = $v['parent2'];
				$comdata['parent2']['nickname'] = $parent2['nickname'];
				$comdata['parent2']['headimg'] = $parent2['headimg'];
				$comdata['parent2']['money'] += $v['parent2commission'];
				$comdata['parent2']['score'] += $v['parent2score'];
			}
			if($v['parent3']){
				$parent3 = Db::name('member')->where('id',$v['parent3'])->find();
				$comdata['parent3']['mid'] = $v['parent3'];
				$comdata['parent3']['nickname'] = $parent3['nickname'];
				$comdata['parent3']['headimg'] = $parent3['headimg'];
				$comdata['parent3']['money'] += $v['parent3commission'];
				$comdata['parent3']['score'] += $v['parent3score'];
			}
            }
		$comdata['parent1']['money'] = round($comdata['parent1']['money'],2);
		$comdata['parent2']['money'] = round($comdata['parent2']['money'],2);
		$comdata['parent3']['money'] = round($comdata['parent3']['money'],2);

		$order['formdata'] = \app\model\Freight::getformdata($order['id'],'shop_order');
		//弃用
		if($order['field1']){
			$order['field1data'] = explode('^_^',$order['field1']);
		}
		if($order['field2']){
			$order['field2data'] = explode('^_^',$order['field2']);
		}
		if($order['field3']){
			$order['field3data'] = explode('^_^',$order['field3']);
		}
		if($order['field4']){
			$order['field4data'] = explode('^_^',$order['field4']);
		}
		if($order['field5']){
			$order['field5data'] = explode('^_^',$order['field5']);
		}
		if($order['freight_type']==11){
			$order['freight_content'] = json_decode($order['freight_content'],true);
		}
		$miandanst = Db::name('admin_set')->where('aid',aid)->value('miandanst');
		if(bid==0 && $miandanst==1 && in_array('wx',$this->platform) && ($member['wxopenid'] || $member['unionid'])){ //可以使用小程序物流助手发货
			$canmiandan = 1;
		}else{
			$canmiandan = 0;
		}
		if($order['checkmemid']){
			$checkmember = Db::name('member')->field('id,nickname,headimg,realname,tel')->where('id',$order['checkmemid'])->find();
		}else{
			$checkmember = [];
		}

        $payorder = [];
        if($order['paytypeid'] == 5) {
            $payorder = Db::name('payorder')->where('id',$order['payorderid'])->where('aid',aid)->find();
            if($payorder) {
                if($payorder['check_status'] === 0) {
                    $payorder['check_status_label'] = '待审核';
                }elseif($payorder['check_status'] == 1) {
                    $payorder['check_status_label'] = '通过';
                }elseif($payorder['check_status'] == 2) {
                    $payorder['check_status_label'] = '驳回';
                }else{
                    $payorder['check_status_label'] = '未上传';
                }
                if($payorder['paypics']) {
                    $payorder['paypics'] = explode(',', $payorder['paypics']);
                    foreach ($payorder['paypics'] as $item) {
                        $payorder['paypics_html'] .= '<img src="'.$item.'" width="200" onclick="preview(this)"/>';
                    }
                }
            }
        }
		if($order['express_content']) $order['express_content'] = json_decode($order['express_content'],true);
		if($order['status'] == 1){
			$order['express_ogids'] = implode(',',$ogids);
		}
		if($order['express_ogids']){
			$order['express_ogids'] = explode(',',$order['express_ogids']);
		}else{
			$order['express_ogids'] = [];
		}
		foreach($order['express_content'] as $k=>$v){
			if(!$v['express_ogids']){
				$v['express_ogids'] = [];
			}else{
				$v['express_ogids'] = explode(',',$v['express_ogids']);
			}
			$order['express_content'][$k] = $v;
		}
		return json(['order'=>$order,'couponrecord'=>$couponrecord,'couponnames'=>$couponnames,'oglist'=>$oglist,'member'=>$member,'comdata'=>$comdata,'canmiandan'=>$canmiandan,'checkmember'=>$checkmember,'payorder' => $payorder]);
	}
	
	//设置备注
	public function setremark(){
		$orderid = input('post.orderid/d');
		$content = input('post.content');
		if(bid == 0){
			Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->update(['remark'=>$content]);
		}else{
			Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('id',$orderid)->update(['remark'=>$content]);
		}
		\app\common\System::plog('商城订单设置备注'.$orderid);
		return json(['status'=>1,'msg'=>'设置完成']);
	}
	//改价格
	public function changeprice(){
		$orderid = input('post.orderid/d');
		$newprice = input('post.newprice/f');
		$newordernum = date('ymdHis').rand(100000,999999);

        $where = [];
        $where[] = ['aid','=',aid];
		if(bid > 0){
            $where[] = ['bid','=',bid];
		}

        $order = Db::name('shop_order')->where($where)->where('id',$orderid)->find();
        $ordernumArr = explode('_',$order['ordernum']);
        if($ordernumArr[1]) $newordernum .= '_'.$ordernumArr[1];
        Db::name('shop_order')->where($where)->where('id',$orderid)->update(['totalprice'=>$newprice,'ordernum'=>$newordernum]);
        Db::name('shop_order_goods')->where($where)->where('orderid',$orderid)->update(['ordernum'=>$newordernum]);

		$payorderid = Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->value('payorderid');

		\app\model\Payorder::updateorder($payorderid,$newordernum,$newprice,$orderid);
		\app\common\System::plog('商城订单改价格'.$orderid);
		return json(['status'=>1,'msg'=>'修改完成']);
	}
	//关闭订单
	public function closeOrder(){
		$orderid = input('post.orderid/d');
		if(bid == 0){
			$order = Db::name('shop_order')->where('id',$orderid)->where('aid',aid)->find();
		}else{
			$order = Db::name('shop_order')->where('id',$orderid)->where('aid',aid)->where('bid',bid)->find();
		}
		if(!$order || $order['status']!=0){
			return json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
		}
		//加库存
		$oglist = Db::name('shop_order_goods')->where('aid',aid)->where('orderid',$orderid)->select()->toArray();
		foreach($oglist as $og){
			Db::name('shop_guige')->where('aid',aid)->where('id',$og['ggid'])->update(['stock'=>Db::raw("stock+".$og['num']),'sales'=>Db::raw("sales-".$og['num'])]);
			Db::name('shop_product')->where('aid',aid)->where('id',$og['proid'])->update(['stock'=>Db::raw("stock+".$og['num']),'sales'=>Db::raw("sales-".$og['num'])]);
			}
		
		//优惠券抵扣的返还
		if($order['coupon_rid']){
			Db::name('coupon_record')->where('aid',aid)->where('mid',$order['mid'])->where('id','in',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
		}
		$rs = Db::name('shop_order')->where('id',$orderid)->where('aid',aid)->update(['status'=>4]);
		Db::name('shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->update(['status'=>4]);
		\app\common\System::plog('商城订单关闭订单'.$orderid);
		return json(['status'=>1,'msg'=>'操作成功']);
	}
	//改为已支付
	public function ispay(){
		if(bid > 0) showmsg('无权限操作');
		$orderid = input('post.orderid/d');
		if(bid == 0){
			Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->update(['status'=>1,'paytime'=>time(),'paytype'=>'后台支付']);
		}else{
			Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('id',$orderid)->update(['status'=>1,'paytime'=>time(),'paytype'=>'后台支付']);
		}
		\app\model\Payorder::shop_pay($orderid);

		//Db::name('shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->where('bid',bid)->update(['status'=>1]);
		////奖励积分
		//$order = Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('id',$orderid)->find();
		//if($order['givescore'] > 0){
		//	\app\common\Member::addscore(aid,$order['mid'],$order['givescore'],'购买产品奖励'.t('积分'));
		//}
		\app\common\System::plog('商城订单改为已支付'.$orderid);
		return json(['status'=>1,'msg'=>'操作成功']);
	}
	//发货
	public function sendExpress(){
		$orderid = input('post.orderid/d');
		if(bid == 0){
			$order = Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->find();
		}else{
			$order = Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('id',$orderid)->find();
		}

        $refundingMoney = Db::name('shop_refund_order')->where('orderid',$order['id'])->where('aid',aid)->whereIn('refund_status',[1,4])->sum('refund_money');
        if($refundingMoney > 0) {
            return json(['status'=>0,'msg'=>'请先处理完进行中的退款单']);
        }

		//如果选择了配送时间，未到配送时间内不可以进行配送
		if($order['status']!=1 && $order['status']!=2){
			return json(['status'=>0,'msg'=>'该订单状态不允许发货']);
		}
		$express_isbufen = 0;
		$expres_content = '';
		if($order['freight_type']==10){
			$pic = input('post.pic');
			$fhname = input('post.fhname');
			$fhaddress = input('post.fhaddress');
			$shname = input('post.shname');
			$shaddress = input('post.shaddress');
			$remark = input('post.remark');
			$data = [];
			$data['aid'] = aid;
			$data['pic'] = $pic;
			$data['fhname'] = $fhname;
			$data['fhaddress'] = $fhaddress;
			$data['shname'] = $shname;
			$data['shaddress'] = $shaddress;
			$data['remark'] = $remark;
			$data['createtime'] = time();
			$id = Db::name('freight_type10_record')->insertGetId($data);
			$express_com = '货运托运';
			$express_no = $id;
		}else{

			$express_comArr = input('post.express_com/a');
			$express_noArr = input('post.express_no/a');
			$express_ogidsArr = input('post.express_ogids/a');

			$express_ogidsAll = [];
			if(count($express_comArr) > 1){
				$express_com = '多单发货';
				$express_no = '';
				$express_content = [];
				foreach($express_comArr as $k=>$v){
					$express_content[] = ['express_com'=>$v,'express_no'=>$express_noArr[$k],'express_ogids'=>$express_ogidsArr[$k]];
					if($express_ogidsArr[$k]){
						foreach(explode(',',$express_ogidsArr[$k]) as $ogid){
							$express_ogidsAll[] = $ogid;
						}
					}
				}
				$express_content = jsonEncode($express_content);
			}else{
				$express_com = $express_comArr[0];
				$express_no = $express_noArr[0];
				$express_ogids = $express_ogidsArr[0];
				foreach(explode(',',$express_ogidsArr[0]) as $ogid){
					$express_ogidsAll[] = $ogid;
				}
			}

			$oglist = Db::name('shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->select()->toArray();
			if(count($oglist) > 1){
				foreach($oglist as $og){
					if(!in_array($og['id'],$express_ogidsAll)){
						$express_isbufen = 1;
					}
				}
			}
		}
		
		if($order['status']!=1){ //修改物流信息
			Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->update(['express_com'=>$express_com,'express_no'=>$express_no,'express_ogids'=>$express_ogids,'express_content'=>$express_content,'express_isbufen'=>$express_isbufen]);
			return json(['status'=>1,'msg'=>'操作成功']);
		}

		Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->update(['express_com'=>$express_com,'express_no'=>$express_no,'express_ogids'=>$express_ogids,'express_content'=>$express_content,'send_time'=>time(),'status'=>2,'express_isbufen'=>$express_isbufen]);
		Db::name('shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->update(['status'=>2]);
		
		if($order['fromwxvideo'] == 1){
			\app\common\Wxvideo::deliverysend($orderid);
		}

		
		//订单发货通知
		$tmplcontent = [];
		$tmplcontent['first'] = '您的订单已发货';
		$tmplcontent['remark'] = '请点击查看详情~';
		$tmplcontent['keyword1'] = $order['title'];
		$tmplcontent['keyword2'] = $express_com;
		$tmplcontent['keyword3'] = $express_no;
		$tmplcontent['keyword4'] = $order['linkman'].' '.$order['tel'];
		\app\common\Wechat::sendtmpl(aid,$order['mid'],'tmpl_orderfahuo',$tmplcontent,m_url('pages/my/usercenter'));
		//订阅消息
		$tmplcontent = [];
		$tmplcontent['thing2'] = $order['title'];
		$tmplcontent['thing7'] = $express_com;
		$tmplcontent['character_string4'] = $express_no;
		$tmplcontent['thing11'] = $order['address'];
		
		$tmplcontentnew = [];
		$tmplcontentnew['thing29'] = $order['title'];
		$tmplcontentnew['thing1'] = $express_com;
		$tmplcontentnew['character_string2'] = $express_no;
		$tmplcontentnew['thing9'] = $order['address'];
		\app\common\Wechat::sendwxtmpl(aid,$order['mid'],'tmpl_orderfahuo',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

		//短信通知
		$member = Db::name('member')->where('id',$order['mid'])->find();
		if($member['tel']){
			$tel = $member['tel'];
		}else{
			$tel = $order['tel'];
		}
		$rs = \app\common\Sms::send(aid,$tel,'tmpl_orderfahuo',['ordernum'=>$order['ordernum'],'express_com'=>$express_com,'express_no'=>$express_no]);
		
		\app\common\System::plog('商城订单发货'.$orderid);
		return json(['status'=>1,'msg'=>'操作成功']);
	}
	//批量发货
	public function plfh(){
		$express_com = input('post.plfh_express');
		$file = input('post.plfh_file');
		$exceldata = $this->import_excel($file);
		//dump($exceldata);
		$countnum = count($exceldata);
		$successnum = 0;
		$errornum = 0;
		foreach($exceldata as $v){
			$ordernum = trim($v[0]);
			$express_no = $v[1];
			$order = Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('ordernum',$ordernum)->find();
			if(!$order || $order['status'] != 1 && $order['status'] != 2){
				$errornum++;
				continue;
			}
			$orderid = $order['id'];
			Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('id',$orderid)->update(['express_com'=>$express_com,'express_no'=>$express_no,'send_time'=>time(),'status'=>2]);
			Db::name('shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->where('bid',bid)->update(['status'=>2]);
			
			if($order['fromwxvideo'] == 1){
				\app\common\Wxvideo::deliverysend($orderid);
			}


		    //订单发货通知
			$tmplcontent = [];
			$tmplcontent['first'] = '您的订单已发货';
			$tmplcontent['remark'] = '请点击查看详情~';
			$tmplcontent['keyword1'] = $order['title'];
			$tmplcontent['keyword2'] = $express_com;
			$tmplcontent['keyword3'] = $express_no;
			$tmplcontent['keyword4'] = $order['linkman'].' '.$order['tel'];
			\app\common\Wechat::sendtmpl(aid,$order['mid'],'tmpl_orderfahuo',$tmplcontent,m_url('pages/my/usercenter'));
			//订阅消息
			$tmplcontent = [];
			$tmplcontent['thing2'] = $order['title'];
			$tmplcontent['thing7'] = $express_com;
			$tmplcontent['character_string4'] = $express_no;
			$tmplcontent['thing11'] = $order['address'];
			
			$tmplcontentnew = [];
			$tmplcontentnew['thing29'] = $order['title'];
			$tmplcontentnew['thing1'] = $express_com;
			$tmplcontentnew['character_string2'] = $express_no;
			$tmplcontentnew['thing9'] = $order['address'];
			\app\common\Wechat::sendwxtmpl(aid,$order['mid'],'tmpl_orderfahuo',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

			//短信通知
			$member = Db::name('member')->where('id',$order['mid'])->find();
			if($member['tel']){
				$tel = $member['tel'];
			}else{
				$tel = $order['tel'];
			}
			$rs = \app\common\Sms::send(aid,$tel,'tmpl_orderfahuo',['ordernum'=>$order['ordernum'],'express_com'=>$express_com,'express_no'=>$express_no]);
			$successnum++;
		}
		\app\common\System::plog('商城订单批量发货');
		return json(['status'=>1,'msg'=>'共导入 '.$countnum.' 条数据，成功发货 '.$successnum.' 条，失败 '.$errornum.' 条']);
	}
    //批量发货-云仓
    public function plfhyc(){
        $file = input('post.plfhyc_file');
        $exceldata = $this->import_excel($file);
//        dd($exceldata);
        $countnum = count($exceldata);
        $successnum = 0;
        $errornum = 0;
        foreach($exceldata as $v){
            $ordernum = $v[1];
            $express_com = $v[4];
            $express_no = $v[5];
            $order = Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('ordernum',$ordernum)->find();
            if(!$order || $order['status'] != 1 && $order['status'] != 2){
                $errornum++;
                continue;
            }
            $orderid = $order['id'];
            Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('id',$orderid)->update(['express_com'=>$express_com,'express_no'=>$express_no,'send_time'=>time(),'status'=>2]);
            Db::name('shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->where('bid',bid)->update(['status'=>2]);

            if($order['fromwxvideo'] == 1){
                \app\common\Wxvideo::deliverysend($orderid);
            }

            //订单发货通知
            $tmplcontent = [];
            $tmplcontent['first'] = '您的订单已发货';
            $tmplcontent['remark'] = '请点击查看详情~';
            $tmplcontent['keyword1'] = $order['title'];
            $tmplcontent['keyword2'] = $express_com;
            $tmplcontent['keyword3'] = $express_no;
            $tmplcontent['keyword4'] = $order['linkman'].' '.$order['tel'];
            \app\common\Wechat::sendtmpl(aid,$order['mid'],'tmpl_orderfahuo',$tmplcontent,m_url('pages/my/usercenter'));
            //订阅消息
            $tmplcontent = [];
            $tmplcontent['thing2'] = $order['title'];
            $tmplcontent['thing7'] = $express_com;
            $tmplcontent['character_string4'] = $express_no;
            $tmplcontent['thing11'] = $order['address'];
			
			$tmplcontentnew = [];
			$tmplcontentnew['thing29'] = $order['title'];
			$tmplcontentnew['thing1'] = $express_com;
			$tmplcontentnew['character_string2'] = $express_no;
			$tmplcontentnew['thing9'] = $order['address'];
            \app\common\Wechat::sendwxtmpl(aid,$order['mid'],'tmpl_orderfahuo',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

            //短信通知
            $member = Db::name('member')->where('id',$order['mid'])->find();
            if($member['tel']){
                $tel = $member['tel'];
            }else{
                $tel = $order['tel'];
            }
            $rs = \app\common\Sms::send(aid,$tel,'tmpl_orderfahuo',['ordernum'=>$order['ordernum'],'express_com'=>$express_com,'express_no'=>$express_no]);
            $successnum++;
        }
        \app\common\System::plog('商城订单批量发货');
        return json(['status'=>1,'msg'=>'共导入 '.$countnum.' 条数据，成功发货 '.$successnum.' 条，失败 '.$errornum.' 条']);
    }
	//查物流
	public function getExpress(){
		$orderid = input('post.orderid/d');
		$order = Db::name('shop_order')->where('id',$orderid)->where('aid',aid)->find();
		if($order['freight_type'] == '10'){
			$data = Db::name('freight_type10_record')->where('id',$order['express_no'])->find();
			return json(['status'=>1,'data'=>$data]);
		}
		if($order['express_content']) {
		    $expressArr = json_decode($order['express_content'],true);
		    foreach ($expressArr as $order) {
                if($order['express_com'] == '顺丰速运'){
                    $totel = $order['tel'];
                    $order['express_no'] = $order['express_no'].":".substr($totel,-4);
                }
				if($order['express_ogids']){
					$oglist = Db::name('shop_order_goods')->where('aid',aid)->where('id','in',$order['express_ogids'])->select()->toArray();
				}else{
					$oglist = [];
				}
                $list[] = [
                    'express_no' => $order['express_no'],
                    'express_com' => $order['express_com'],
                    'express_data' => \app\common\Common::getwuliu($order['express_no'],$order['express_com'],$order['express_type']),
					'oglist'=>$oglist,
                ];
            }

        } else {
            if($order['express_com'] == '顺丰速运'){
                $totel = $order['tel'];
                $order['express_no'] = $order['express_no'].":".substr($totel,-4);
            }
			if($order['express_ogids']){
				$oglist = Db::name('shop_order_goods')->where('aid',aid)->where('id','in',$order['express_ogids'])->select()->toArray();
			}else{
				$oglist = [];
			}
            $list[] = [
                'express_no' => $order['express_no'],
                'express_com' => $order['express_com'],
                'express_data' => \app\common\Common::getwuliu($order['express_no'],$order['express_com'],$order['express_type']),
				'oglist'=>$oglist,
            ];
        }

		return json(['status'=>1,'data'=>$list]);
	}
    //付款审核
    public function payCheck(){
        }
	//退款审核
	public function refundCheck(){
		$orderid = input('post.orderid/d');
		$st = input('post.st/d');
		$remark = input('post.remark');
		if(bid == 0){
			$order = Db::name('shop_order')->where('id',$orderid)->where('aid',aid)->find();
		}else{
			$order = Db::name('shop_order')->where('id',$orderid)->where('aid',aid)->where('bid',bid)->find();
		}
		if(!$order) return json(['status'=>1,'msg'=>'订单不存在']);
		if($st==2){
			Db::name('shop_order')->where('id',$orderid)->where('aid',aid)->update(['refund_status'=>3,'refund_checkremark'=>$remark]);
			//退款申请驳回通知
			$tmplcontent = [];
			$tmplcontent['first'] = '您的退款申请被商家驳回，可与商家协商沟通。';
			$tmplcontent['remark'] = $remark.'，请点击查看详情~';
			$tmplcontent['orderProductPrice'] = $order['refund_money'].'元';
			$tmplcontent['orderProductName'] = $order['title'];
			$tmplcontent['orderName'] = $order['ordernum'];
			\app\common\Wechat::sendtmpl(aid,$order['mid'],'tmpl_tuierror',$tmplcontent,m_url('pages/my/usercenter'));
			//订阅消息
			$tmplcontent = [];
			$tmplcontent['amount3'] = $order['refund_money'];
			$tmplcontent['thing2'] = $order['title'];
			$tmplcontent['character_string1'] = $order['ordernum'];
			
			$tmplcontentnew = [];
			$tmplcontentnew['amount3'] = $order['refund_money'];
			$tmplcontentnew['thing8'] = $order['title'];
			$tmplcontentnew['character_string4'] = $order['ordernum'];
			\app\common\Wechat::sendwxtmpl(aid,$order['mid'],'tmpl_tuierror',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);
			//短信通知
			$member = Db::name('member')->where('id',$order['mid'])->find();
			if($member['tel']){
				$tel = $member['tel'];
			}else{
				$tel = $order['tel'];
			}
			$rs = \app\common\Sms::send(aid,$tel,'tmpl_tuierror',['ordernum'=>$order['ordernum'],'reason'=>$remark]);
			\app\common\System::plog('商城订单退款驳回'.$orderid);
			return json(['status'=>1,'msg'=>'退款已驳回']);
		}elseif($st == 1){
			if($order['status']!=1 && $order['status']!=2){
				return json(['status'=>0,'msg'=>'该订单状态不允许退款']);
			}
			if($order['refund_money'] > 0){
				$rs = \app\common\Order::refund($order,$order['refund_money'],$order['refund_reason']);
				if($rs['status']==0){
					return json(['status'=>0,'msg'=>$rs['msg']]);
				}
			}

			Db::name('shop_order')->where('id',$orderid)->where('aid',aid)->update(['status'=>4,'refund_status'=>2,'refund_checkremark'=>$remark]);
			Db::name('shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->update(['status'=>4]);

			//积分抵扣的返还
			if($order['scoredkscore'] > 0){
				\app\common\Member::addscore(aid,$order['mid'],$order['scoredkscore'],'订单退款返还');
			}
			if($order['givescore2'] > 0){
                \app\common\Member::addscore(aid,$order['mid'],-$order['givescore2'],'订单退款扣除');
            }
			//优惠券抵扣的返还
			if($order['coupon_rid']){
				Db::name('coupon_record')->where('aid',aid)->where('mid',$order['mid'])->where('id','in',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
			}

			//元宝返回
            //退款成功通知
			$tmplcontent = [];
			$tmplcontent['first'] = '您的订单已经完成退款，¥'.$order['refund_money'].'已经退回您的付款账户，请留意查收。';
			$tmplcontent['remark'] = $remark.'，请点击查看详情~';
			$tmplcontent['orderProductPrice'] = $order['refund_money'].'元';
			$tmplcontent['orderProductName'] = $order['title'];
			$tmplcontent['orderName'] = $order['ordernum'];
			\app\common\Wechat::sendtmpl(aid,$order['mid'],'tmpl_tuisuccess',$tmplcontent,m_url('pages/my/usercenter'));
			//订阅消息
			$tmplcontent = [];
			$tmplcontent['amount6'] = $order['refund_money'];
			$tmplcontent['thing3'] = $order['title'];
			$tmplcontent['character_string2'] = $order['ordernum'];
			
			$tmplcontentnew = [];
			$tmplcontentnew['amount3'] = $order['refund_money'];
			$tmplcontentnew['thing6'] = $order['title'];
			$tmplcontentnew['character_string4'] = $order['ordernum'];
			\app\common\Wechat::sendwxtmpl(aid,$order['mid'],'tmpl_tuisuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

			//短信通知
			$member = Db::name('member')->where('id',$order['mid'])->find();
			if($member['tel']){
				$tel = $member['tel'];
			}else{
				$tel = $order['tel'];
			}
			$rs = \app\common\Sms::send(aid,$tel,'tmpl_tuisuccess',['ordernum'=>$order['ordernum'],'money'=>$order['refund_money']]);
			
			\app\common\System::plog('商城订单退款审核通过并退款'.$orderid);
			return json(['status'=>1,'msg'=>'已退款成功']);
		}
	}
    //退款
    public function refundinit(){
        //查询订单信息
        $detail = Db::name('shop_order')->where('id',input('param.orderid/d'))->where('aid',aid)->find();
        if(!$detail)
            return json(['status'=>0,'msg'=>'订单不存在']);
        $detail['createtime'] = $detail['createtime'] ? date('Y-m-d H:i:s',$detail['createtime']) : '';
        $detail['collect_time'] = $detail['collect_time'] ? date('Y-m-d H:i:s',$detail['collect_time']) : '';
        $detail['paytime'] = $detail['paytime'] ? date('Y-m-d H:i:s',$detail['paytime']) : '';
        $detail['refund_time'] = $detail['refund_time'] ? date('Y-m-d H:i:s',$detail['refund_time']) : '';
        $detail['send_time'] = $detail['send_time'] ? date('Y-m-d H:i:s',$detail['send_time']) : '';

        $refundMoneySum = Db::name('shop_refund_order')->where('orderid',$detail['id'])->where('aid',aid)->whereIn('refund_status',[1,2,4])->sum('refund_money');

        $canRefundNum = 0;
        $totalNum = 0;
        $returnTotalprice = 0;
        $prolist = Db::name('shop_order_goods')->where('orderid',$detail['id'])->select()->toArray();
        foreach ($prolist as $key => $item) {
            $prolist[$key]['canRefundNum'] = $item['num'] - $item['refund_num'];
            $totalNum += $item['num'];
            $canRefundNum += $item['num'] - $item['refund_num'];
//            $returnTotalprice += $item['real_totalprice'] / $item['num'] * ($item['num'] - $item['refund_num']);
        }
        if($canRefundNum == $totalNum) {
            $returnTotalprice = $detail['totalprice'];
        } else {
            $returnTotalprice = $detail['totalprice'] - $refundMoneySum;
        }
        //可退款金额=总金额-审核中-已退款
        $detail['canRefundNum'] = $canRefundNum;
        $detail['totalNum'] = $totalNum;
        $detail['returnTotalprice'] = $returnTotalprice;
//        if($canRefundNum == 0) {
//            return $this->json(['status'=>0,'msg'=>'当前订单没有可退款的商品']);
//        }
        //todo 确认收货后的退款

        $rdata = [];
        $rdata['status'] = 1;
        $rdata['detail'] = $detail;
        $rdata['prolist'] = $prolist;

        return json($rdata);
    }
	//退款
	public function refund(){
		$orderid = input('post.orderid/d');
		$reason = input('post.reason');
		if(bid == 0){
			$order = Db::name('shop_order')->where('id',$orderid)->where('aid',aid)->find();
		}else{
			$order = Db::name('shop_order')->where('id',$orderid)->where('aid',aid)->where('bid',bid)->find();
		}
		if(!$order) return json(['status'=>0,'msg'=>'订单不存在']);
		if($order['status']!=1 && $order['status']!=2){
			return json(['status'=>0,'msg'=>'该订单状态不允许退款']);
		}
        $refundingMoney = Db::name('shop_refund_order')->where('orderid',$order['id'])->where('aid',aid)->whereIn('refund_status',[1,4])->sum('refund_money');
		if($refundingMoney) {
            return json(['status'=>0,'msg'=>'请先处理完进行中的退款单']);
        }
//        $refundedMoney = Db::name('shop_refund_order')->where('orderid',$order['id'])->where('aid',aid)->where('bid',bid)->where('refund_status',2)->sum('refund_money');
//        $refund_money -= $refundedMoney;

        try {
            Db::startTrans();
            //新退款 202108
            $post = input('post.');
            $orderid = intval($post['orderid']);
            $money = floatval($post['money']);
            $refundNum = $post['refundNum'];
            $order = Db::name('shop_order')->where('aid', aid)->where('id', $orderid)->find();
            if (!$order || ($order['status'] != 1 && $order['status'] != 2)) {
                return json(['status' => 0, 'msg' => '订单状态不符合退款要求']);
            }
            if ($money < 0 || $money > $order['totalprice']) {
                return json(['status' => 0, 'msg' => '退款金额有误']);
            }
            if (empty($refundNum)) {
                return json(['status' => 0, 'msg' => '请选择退款的商品']);
            }

            $totalRefundNum = 0;
            $returnTotalprice = 0;
            $prolist = Db::name('shop_order_goods')->where('orderid', $orderid)->select();
            $newKey = 'id';
            $prolist = $prolist->dictionary(null, $newKey);
            $ogids = array_keys($prolist);

            $refundMoneySum = Db::name('shop_refund_order')->where('orderid', $orderid)->where('aid', aid)->whereIn('refund_status', [1, 2, 4])->sum('refund_money');

            $canRefundNum = 0;
            $totalNum = 0;
            $canRefundProductPrice = 0;
            $canRefundTotalprice = 0;
            foreach ($prolist as $key => $item) {
                $prolist[$key]['canRefundNum'] = $item['num'] - $item['refund_num'];
                $totalNum += $item['num'];
                $canRefundNum += $item['num'] - $item['refund_num'];
                $canRefundProductPrice += $item['real_totalprice'] / $item['num'] * ($item['num'] - $item['refund_num']);
            }

            foreach ($refundNum as $item) {
                if (!in_array($item['ogid'], $ogids)) {
                    return json(['status' => 0, 'msg' => '退款商品不存在']);
                }
                if ($item['num'] > $prolist[$item['ogid']]['num'] - $prolist[$item['ogid']]['refund_num']) {
                    return json(['status' => 0, 'msg' => $prolist[$item['ogid']]['name'] . '退款数量超出范围']);
                }
                $totalRefundNum += $item['num'];
                //            $returnTotalprice += $prolist[$item['ogid']]['real_totalprice'] / $prolist[$item['ogid']]['num'] * $item['num'];
            }
            if ($totalRefundNum == 0) {
                return json(['status' => 0, 'msg' => '请选择退款的商品']);
            }
            if ($canRefundNum == $totalNum && $totalNum == $totalRefundNum) {
                $canRefundTotalprice = $order['totalprice'];
            } else {
                $canRefundTotalprice = $order['totalprice'] - $refundMoneySum;
            }

            if ($money > $canRefundTotalprice) {
                return json(['status' => 0, 'msg' => '退款金额超出范围']);
            }

            $data = [
                'aid' => $order['aid'],
                'bid' => $order['bid'],
                'mdid' => $order['mdid'],
                'mid' => $order['mid'],
                'orderid' => $order['id'],
                'ordernum' => $order['ordernum'],
                'refund_type' => 'refund',
                'refund_ordernum' => '' . date('ymdHis') . rand(100000, 999999),
                'refund_money' => $money,
                'refund_reason' => '后台退款：' . $post['reason'],
                'refund_pics' => '',
                'createtime' => time(),
                'refund_time' => time(),
                'refund_status' => 2,
                'platform' => platform,
            ];
            $refund_id = Db::name('shop_refund_order')->insertGetId($data);

            if ($order['fromwxvideo'] == 1) {
                \app\common\Wxvideo::aftersaleadd($order['id'], $refund_id);
            }
            if ($data['refund_money'] > 0) {
                $rs = \app\common\Order::refund($order, $data['refund_money'], $reason);
                if ($rs['status'] == 0) {
                    Db::name('shop_refund_order')->where('id', $refund_id)->delete();
                    return json(['status' => 0, 'msg' => $rs['msg']]);
                }
            }

            foreach ($refundNum as $item) {
                if ($item['num'] < 1) continue;
                $od = [
                    'aid' => $order['aid'],
                    'bid' => $order['bid'],
                    'mid' => $order['mid'],
                    'orderid' => $order['id'],
                    'ordernum' => $order['ordernum'],
                    'refund_orderid' => $refund_id,
                    'refund_ordernum' => $data['refund_ordernum'],
                    'refund_num' => $item['num'],
                    'refund_money' => $item['num'] * $prolist[$item['ogid']]['real_totalprice'] / $prolist[$item['ogid']]['num'],
                    'ogid' => $item['ogid'],
                    'proid' => $prolist[$item['ogid']]['proid'],
                    'name' => $prolist[$item['ogid']]['name'],
                    'pic' => $prolist[$item['ogid']]['pic'],
                    'procode' => $prolist[$item['ogid']]['procode'],
                    'ggid' => $prolist[$item['ogid']]['ggid'],
                    'ggname' => $prolist[$item['ogid']]['ggname'],
                    'cid' => $prolist[$item['ogid']]['cid'],
                    'cost_price' => $prolist[$item['ogid']]['cost_price'],
                    'sell_price' => $prolist[$item['ogid']]['sell_price'],
                    'createtime' => time()
                ];
                Db::name('shop_refund_order_goods')->insertGetId($od);
                Db::name('shop_order_goods')->where('aid', aid)->where('id', $item['ogid'])->inc('refund_num', $item['num'])->update();
            }

            //        $order_goods = Db::name('shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->where('bid',bid)->fieldRaw('ggid,proid,num,refund_num, num-refund_num as true_num')->select()->toArray();
            //		Db::name('shop_order')->where('id',$orderid)->where('aid',aid)->where('bid',bid)->update(['status'=>4,'refund_status'=>2,'refund_money'=>$refund_money,'refund_reason'=>$reason]);
            //		Db::name('shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->where('bid',bid)->update(['status'=>4,'refund_num' => Db::raw('num')]);

            //恢复库存 删除销量
            foreach ($refundNum as $item) {
                Db::name('shop_guige')->where('aid', aid)->where('id', $prolist[$item['ogid']]['ggid'])->update(['stock' => Db::raw("stock+" . $item['num']), 'sales' => Db::raw("sales-" . $item['num'])]);
                Db::name('shop_product')->where('aid', aid)->where('id', $prolist[$item['ogid']]['proid'])->update(['stock' => Db::raw("stock+" . $item['num']), 'sales' => Db::raw("sales-" . $item['num'])]);

                }

            //整单全部退时 返还积分和优惠券
            if ($totalRefundNum == $canRefundNum && $money == $canRefundTotalprice) {
                Db::name('shop_order')->where('id', $order['id'])->where('aid', aid)->update(['status' => 4, 'refund_status' => 2, 'refund_money' => $refundMoneySum + $data['refund_money']]);
                Db::name('shop_order_goods')->where('orderid', $order['id'])->where('aid', aid)->update(['status' => 4]);
                //积分抵扣的返还
                if ($order['scoredkscore'] > 0) {
                    \app\common\Member::addscore(aid, $order['mid'], $order['scoredkscore'], '订单退款返还');
                }
                if ($order['givescore2'] > 0) {
                    \app\common\Member::addscore(aid, $order['mid'], -$order['givescore2'], '订单退款扣除');
                }
                //优惠券抵扣的返还
                if ($order['coupon_rid']) {
                    Db::name('coupon_record')->where('aid', aid)->where('mid', $order['mid'])->where('id', 'in', $order['coupon_rid'])->update(['status' => 0, 'usetime' => '']);
                }
                //元宝返回
                if ($order['givescore2'] > 0) {
                    \app\common\Member::addscore(aid, $order['mid'], -$order['givescore2'], '订单退款扣除');
                }
            } else {
                //部分退款
                Db::name('shop_order')->where('id', $order['id'])->where('aid', aid)->inc('refund_money', $data['refund_money'])->update(['refund_status' => 2]);
                //重新计算佣金
                $prolist = Db::name('shop_order_goods')->where('orderid', $order['id'])->where('aid', aid)->select();
                $reog = Db::name('shop_refund_order_goods')->where('refund_orderid', $refund_id)->select();
                \app\common\Order::updateCommission($prolist, $reog);
            }

            //		//积分抵扣的返还
            //		if($order['scoredkscore'] > 0){
            //			\app\common\Member::addscore(aid,$order['mid'],$order['scoredkscore'],'订单退款返还');
            //		}
            //		//优惠券抵扣的返还
            //		if($order['coupon_rid'] > 0){
            //			Db::name('coupon_record')->where('aid',aid)->where(['mid'=>$order['mid'],'id'=>$order['coupon_rid']])->update(['status'=>0,'usetime'=>'']);
            //		}

            Db::commit();
        } catch (\Exception $e) {
            Log::write([
                'file' => __FILE__ . ' L' . __LINE__,
                'function' => __FUNCTION__,
                'error' => $e->getMessage(),
            ]);
            Db::rollback();
            return json(['status'=>0,'msg'=>'提交失败,请重试']);
        }

        $refund_money = $data['refund_money'];
		//退款成功通知
		$tmplcontent = [];
		$tmplcontent['first'] = '您的订单已经完成退款，¥'.$refund_money.'已经退回您的付款账户，请留意查收。';
		$tmplcontent['remark'] = $reason.'，请点击查看详情~';
		$tmplcontent['orderProductPrice'] = $refund_money.'元';
		$tmplcontent['orderProductName'] = $order['title'];
		$tmplcontent['orderName'] = $order['ordernum'];
		\app\common\Wechat::sendtmpl(aid,$order['mid'],'tmpl_tuisuccess',$tmplcontent,m_url('pages/my/usercenter'));
		//订阅消息
		$tmplcontent = [];
		$tmplcontent['amount6'] = $refund_money;
		$tmplcontent['thing3'] = $order['title'];
		$tmplcontent['character_string2'] = $order['ordernum'];
		
		$tmplcontentnew = [];
		$tmplcontentnew['amount3'] = $refund_money;
		$tmplcontentnew['thing6'] = $order['title'];
		$tmplcontentnew['character_string4'] = $order['ordernum'];
		\app\common\Wechat::sendwxtmpl(aid,$order['mid'],'tmpl_tuisuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

		//短信通知
		$member = Db::name('member')->where('id',$order['mid'])->find();
		if($member['tel']){
			$tel = $member['tel'];
		}else{
			$tel = $order['tel'];
		}
		$rs = \app\common\Sms::send(aid,$tel,'tmpl_tuisuccess',['ordernum'=>$order['ordernum'],'money'=>$refund_money]);
		
		\app\common\System::plog('商城订单退款'.$orderid);
		return json(['status'=>1,'msg'=>'已退款成功']);
	}

	//核销并确认收货
    function orderHexiao(){
        $post = input('post.');
        $orderid = intval($post['orderid']);
		if(bid == 0){
			$order = Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->find();
		}else{
			$order = Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('id',$orderid)->find();
		}
        if(!$order || !in_array($order['status'], [1,2]) || $order['freight_type'] != 1){
            return json(['status'=>0,'msg'=>'订单状态不符合核销收货要求']);
        }

        $refundOrder = Db::name('shop_refund_order')->where('refund_status','in',[1,4])->where('aid',aid)->where('orderid',$orderid)->count();
        if($refundOrder){
            return json(['status'=>0,'msg'=>'有正在进行的退款，无法核销']);
        }

        $data = array();
        $data['aid'] = aid;
        $data['bid'] = $order['bid'];
        $data['uid'] = $this->uid;
        $data['mid'] = $order['mid'];
        $data['orderid'] = $order['id'];
        $data['ordernum'] = $order['ordernum'];
        $data['title'] = $order['title'];
        $data['type'] = 'shop';
        $data['createtime'] = time();
        $data['remark'] = '核销员['.$this->user['un'].']核销';
        Db::name('hexiao_order')->insert($data);

        $rs = \app\common\Order::collect($order, 'shop', $this->user['mid']);
        if($rs['status']==0) return $rs;
        Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->update(['status'=>3,'collect_time'=>time()]);
        Db::name('shop_order_goods')->where('aid',aid)->where('orderid',$orderid)->update(['status'=>3,'endtime'=>time()]);
        \app\common\Member::uplv(aid,$order['mid']);
        \app\common\System::plog('商城订单核销确认收货'.$orderid);
        return json(['status'=>1,'msg'=>'核销成功']);
    }
	function orderCollect(){ //确认收货
		$post = input('post.');
		$orderid = intval($post['orderid']);
		$order = Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->find();
		if(bid != 0 && $order['paytypeid'] != 4){
			return json(['status'=>0,'msg'=>'无操作权限']);
		}
		if(!$order || ($order['status']!=2)){
			return json(['status'=>0,'msg'=>'订单状态不符合收货要求']);
		}

        $refundOrder = Db::name('shop_refund_order')->where('refund_status','in',[1,4])->where('aid',aid)->where('orderid',$orderid)->count();
        if($refundOrder){
            return json(['status'=>0,'msg'=>'有正在进行的退款，无法确认收货']);
        }
		$rs = \app\common\Order::collect($order, 'shop', $this->user['mid']);
		if($rs['status']==0) return $rs;
		Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->update(['status'=>3,'collect_time'=>time()]);
		Db::name('shop_order_goods')->where('aid',aid)->where('orderid',$orderid)->update(['status'=>3,'endtime'=>time()]);
		\app\common\Member::uplv(aid,$order['mid']);
		\app\common\System::plog('商城订单确认收货'.$orderid);
		return json(['status'=>1,'msg'=>'确认收货成功']);
	}
	//打印小票
	public function wifiprint(){
		$id = input('post.id/d');
		$rs = \app\common\Wifiprint::print(aid,'shop',$id,0);
		return json($rs);
	}
	//删除
	public function del(){
		$id = input('post.id/d');
		if(bid == 0){
			Db::name('shop_order')->where('aid',aid)->where('id',$id)->delete();
			Db::name('shop_order_goods')->where('aid',aid)->where('orderid',$id)->delete();

			Db::name('shop_refund_order')->where('aid',aid)->where('orderid',$id)->delete();
			Db::name('shop_refund_order_goods')->where('aid',aid)->where('orderid',$id)->delete();
		}else{
			Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('id',$id)->delete();
			Db::name('shop_order_goods')->where('aid',aid)->where('bid',bid)->where('orderid',$id)->delete();

			Db::name('shop_refund_order')->where('aid',aid)->where('bid',bid)->where('orderid',$id)->delete();
			Db::name('shop_refund_order_goods')->where('aid',aid)->where('bid',bid)->where('orderid',$id)->delete();
		}
        Db::name('invoice')->where('aid',aid)->where('bid',bid)->where('order_type','shop')->where('orderid',$id)->delete();
		\app\common\System::plog('商城订单删除'.$id);
		return json(['status'=>1,'msg'=>'删除成功']);
	}
	//编辑
	public function edit(){
		$orderid = input('param.id/d');
		$info = Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('id',$orderid)->find();
		if(!$info) return json(['status'=>1,'msg'=>'删除成功']);
		$order_goods = Db::name('shop_order_goods')->where('aid',aid)->where('bid',bid)->where('orderid',$orderid)->select()->toArray();
		foreach($order_goods as $k=>$v){
			$order_goods[$k]['lvprice'] = Db::name('shop_product')->where('id',$v['proid'])->value('lvprice'); //是否开启会员价
		}
		$member = Db::name('member')->where('id',$info['mid'])->find();
		$userlevel = Db::name('member_level')->where('aid',aid)->where('id',$member['levelid'])->find();
		if($userlevel && $userlevel['discount']>0 && $userlevel['discount']<10){
			$discount = $userlevel['discount']*0.1; //会员折扣
		}else{
			$discount = 1;
		}

		if(request()->isAjax()){
			$postinfo = input('post.info/a');
			$product_price = $postinfo['product_price'];
			Db::name('shop_order')->where('id',$orderid)->update($postinfo);
			$order = Db::name('shop_order')->where('id',$orderid)->find();
			$sysset = Db::name('admin_set')->where('aid',aid)->find();
			$mid = $order['mid'];
			//是否是复购
			$hasordergoods = Db::name('shop_order_goods')->where('aid',aid)->where('mid',$mid)->where('createtime','<',$order['createtime'])->where('status','in','1,2,3')->find();
			if($hasordergoods){
				$isfg = 1;
			}else{
				$isfg = 0;
			}
			$goods_id = input('post.goods_id/a');
			$goods_ggname = input('post.goods_ggname/a');
			$goods_sell_price = input('post.goods_sell_price/a');
			$goods_num = input('post.goods_num/a');
			foreach($goods_id as $k=>$ogid){
				$oginfo = Db::name('shop_order_goods')->where('id',$ogid)->find();
				$ogdata = [];
				$ogdata['ggname'] = $goods_ggname[$k];
				$ogdata['sell_price'] = $goods_sell_price[$k];
				$ogdata['num'] = $goods_num[$k];
				$ogdata['totalprice'] = $ogdata['sell_price'] * $ogdata['num'];
				
				$product = Db::name('shop_product')->where('id',$oginfo['proid'])->find();
				
				$num = $ogdata['num'];
				$og_totalprice = $ogdata['totalprice'];
				if($product['balance'] > 0){
					$og_totalprice = $og_totalprice * (1 - $product['balance']*0.01);
				}

                $allproduct_price = $product_price;
                $og_leveldk_money = 0;
                $og_coupon_money = 0;
                $og_scoredk_money = 0;
                $og_manjian_money = 0;
                if($allproduct_price > 0 && $og_totalprice > 0){
                    if($leveldk_money){
                        $og_leveldk_money = $og_totalprice / $allproduct_price * $leveldk_money;
                    }
                    if($coupon_money){
                        $og_coupon_money = $og_totalprice / $allproduct_price * $coupon_money;
                    }
                    if($scoredk_money){
                        $og_scoredk_money = $og_totalprice / $allproduct_price * $scoredk_money;
                    }
                    if($manjian_money){
                        $og_manjian_money = $og_totalprice / $allproduct_price * $manjian_money;
                    }
                }
                $ogdata['scoredk_money'] = $og_scoredk_money;
                $ogdata['leveldk_money'] = $og_leveldk_money;
                $ogdata['manjian_money'] = $og_manjian_money;
                $ogdata['coupon_money'] = $og_coupon_money;
                if($product['bid'] > 0) {
                    $totalprice_business = $og_totalprice - $og_manjian_money - $og_coupon_money;
                    //商品独立费率
                    if($product['feepercent'] != '' && $product['feepercent'] != null && $product['feepercent'] >= 0) {
                        $ogdata['business_total_money'] = $totalprice_business * (100-$product['feepercent']) * 0.01;
                    } else {
                        //商户费率
                        $ogdata['business_total_money'] = $totalprice_business * (100-$store_info['feepercent']) * 0.01;
                    }
                }

				//计算商品实际金额  商品金额 - 会员折扣 - 积分抵扣 - 满减抵扣 - 优惠券抵扣
				if($sysset['fxjiesuantype'] == 1 || $sysset['fxjiesuantype'] == 2){
					$og_totalprice = $og_totalprice - $og_leveldk_money - $og_scoredk_money - $og_manjian_money;
					if($couponrecord['type']!=4) {//运费抵扣券
						$og_totalprice -= $og_coupon_money;
					}
					$og_totalprice = round($og_totalprice,2);
					if($og_totalprice < 0) $og_totalprice = 0;
				}
				$ogdata['real_totalprice'] = $og_totalprice; //实际商品销售金额
				
				//计算佣金的商品金额
				$commission_totalprice = $ogdata['totalprice'];
				if($sysset['fxjiesuantype']==1){ //按成交价格
					$commission_totalprice = $ogdata['real_totalprice'];
					if($commission_totalprice < 0) $commission_totalprice = 0;
				}
				$commission_totalpriceCache = $commission_totalprice;
				if($sysset['fxjiesuantype']==2){ //按销售利润
					$commission_totalprice = $ogdata['real_totalprice'] - $guige['cost_price'] * $num;
					if($commission_totalprice < 0) $commission_totalprice = 0;
				}
                Db::name('shop_order_goods')->where('id',$ogid)->update($ogdata);
				
				$hasff = Db::name('member_commission_record')->where('aid',aid)->where('orderid',$orderid)->where('ogid',$ogid)->where('type','shop')->where('status',1)->find();
				//佣金没有发放 重新计算佣金
				if(!$hasff){
					Db::name('member_commission_record')->where('aid',aid)->where('orderid',$orderid)->where('ogid',$ogid)->where('type','shop')->delete();
					$ogupdate = [];
					$agleveldata = Db::name('member_level')->where('aid',aid)->where('id',$member['levelid'])->find();
					if($agleveldata['can_agent'] > 0 && $agleveldata['commission1own']==1){
						$member['pid'] = $mid;
					}
					if($product['commissionset']!=-1){
						if($member['pid']){
							$parent1 = Db::name('member')->where('aid',aid)->where('id',$member['pid'])->find();
							if($parent1){
								$agleveldata1 = Db::name('member_level')->where('aid',aid)->where('id',$parent1['levelid'])->find();
								if($agleveldata1['can_agent']!=0){
									$ogupdate['parent1'] = $parent1['id'];
								}
							}
						}
						if($parent1['pid']){
							$parent2 = Db::name('member')->where('aid',aid)->where('id',$parent1['pid'])->find();
							if($parent2){
								$agleveldata2 = Db::name('member_level')->where('aid',aid)->where('id',$parent2['levelid'])->find();
								if($agleveldata2['can_agent']>1){
									$ogupdate['parent2'] = $parent2['id'];
								}
							}
						}
						if($parent2['pid']){
							$parent3 = Db::name('member')->where('aid',aid)->where('id',$parent2['pid'])->find();
							if($parent3){
								$agleveldata3 = Db::name('member_level')->where('aid',aid)->where('id',$parent3['levelid'])->find();
								if($agleveldata3['can_agent']>2){
									$ogupdate['parent3'] = $parent3['id'];
								}
							}
						}
						if($parent3['pid']){
							$parent4 = Db::name('member')->where('aid',aid)->where('id',$parent3['pid'])->find();
							if($parent4){
								$agleveldata4 = Db::name('member_level')->where('aid',aid)->where('id',$parent4['levelid'])->find();
								//持续推荐奖励
								if($agleveldata4['can_agent'] > 0 && ($agleveldata4['commission_parent'] > 0 || ($parent4['levelid']==$parent3['levelid'] && $agleveldata4['commission_parent_pj'] > 0))){
									$ogupdate['parent4'] = $parent4['id'];
								}
							}
						}
						if($product['commissionset']==1){//按商品设置的分销比例
							$commissiondata = json_decode($product['commissiondata1'],true);
							if($commissiondata){
								if($agleveldata1) $ogupdate['parent1commission'] = $commissiondata[$agleveldata1['id']]['commission1'] * $commission_totalprice * 0.01;
								if($agleveldata2) $ogupdate['parent2commission'] = $commissiondata[$agleveldata2['id']]['commission2'] * $commission_totalprice * 0.01;
								if($agleveldata3) $ogupdate['parent3commission'] = $commissiondata[$agleveldata3['id']]['commission3'] * $commission_totalprice * 0.01;
							}
						}elseif($product['commissionset']==2){//按固定金额
							$commissiondata = json_decode($product['commissiondata2'],true);
							if($commissiondata){
								if(false){}else{
									if($agleveldata1) $ogupdate['parent1commission'] = $commissiondata[$agleveldata1['id']]['commission1'] * $num;
									if($agleveldata2) $ogupdate['parent2commission'] = $commissiondata[$agleveldata2['id']]['commission2'] * $num;
									if($agleveldata3) $ogupdate['parent3commission'] = $commissiondata[$agleveldata3['id']]['commission3'] * $num;
								}
							}
						}elseif($product['commissionset']==3){//提成是积分
							$commissiondata = json_decode($product['commissiondata3'],true);
							if($commissiondata){
								if($agleveldata1) $ogupdate['parent1score'] = $commissiondata[$agleveldata1['id']]['commission1'] * $num;
								if($agleveldata2) $ogupdate['parent2score'] = $commissiondata[$agleveldata2['id']]['commission2'] * $num;
								if($agleveldata3) $ogupdate['parent3score'] = $commissiondata[$agleveldata3['id']]['commission3'] * $num;
							}
						}else{ //按会员等级设置的分销比例
							if($agleveldata1){
								if($agleveldata1['commissiontype']==1){ //固定金额按单
									if($istc1==0){
										$ogupdate['parent1commission'] = $agleveldata1['commission1'];
										$istc1 = 1;
									}
								}else{
									$ogupdate['parent1commission'] = $agleveldata1['commission1'] * $commission_totalprice * 0.01;
								}
							}
							if($agleveldata2){
								if($agleveldata2['commissiontype']==1){
									if($istc2==0){
										$ogupdate['parent2commission'] = $agleveldata2['commission2'];
										$istc2 = 1;
										//持续推荐奖励
										if($agleveldata2['commission_parent'] > 0) {
											$ogupdate['parent2commission'] = $ogupdate['parent2commission'] + $agleveldata2['commission_parent'];
										}
										if($agleveldata1['id'] == $agleveldata2['id'] && $agleveldata2['commission_parent_pj'] > 0) {
											$ogupdate['parent2commission'] = $ogupdate['parent2commission'] + $agleveldata2['commission_parent_pj'];
										}
									}
								}else{
									$ogupdate['parent2commission'] = $agleveldata2['commission2'] * $commission_totalprice * 0.01;
									//持续推荐奖励
									if($agleveldata2['commission_parent'] > 0 && $ogupdate['parent1commission'] > 0) {
										$ogupdate['parent2commission'] = $ogupdate['parent2commission'] + $ogupdate['parent1commission'] * $agleveldata2['commission_parent'] * 0.01;
									}
									if($agleveldata1['id'] == $agleveldata2['id'] && $agleveldata2['commission_parent_pj'] > 0 && $ogupdate['parent1commission'] > 0) {
										$ogupdate['parent2commission'] = $ogupdate['parent2commission'] + $ogupdate['parent1commission'] * $agleveldata2['commission_parent_pj'] * 0.01;
									}
								}
							}
							if($agleveldata3){
								if($agleveldata3['commissiontype']==1){
									if($istc3==0){
										$ogupdate['parent3commission'] = $agleveldata3['commission3'];
										$istc3 = 1;
										//持续推荐奖励
										if($agleveldata3['commission_parent'] > 0) {
											$ogupdate['parent3commission'] = $ogupdate['parent3commission'] + $agleveldata3['commission_parent'];
										}
										if($agleveldata2['id'] == $agleveldata3['id'] && $agleveldata3['commission_parent_pj'] > 0) {
											$ogupdate['parent3commission'] = $ogupdate['parent3commission'] + $agleveldata3['commission_parent_pj'];
										}
									}
								}else{
									$ogupdate['parent3commission'] = $agleveldata3['commission3'] * $commission_totalprice * 0.01;
									//持续推荐奖励
									if($agleveldata3['commission_parent'] > 0 && $ogupdate['parent2commission'] > 0) {
										$ogupdate['parent3commission'] = $ogupdate['parent3commission'] + $ogupdate['parent2commission'] * $agleveldata3['commission_parent'] * 0.01;
									}
									if($agleveldata2['id'] == $agleveldata3['id'] && $agleveldata3['commission_parent_pj'] > 0 && $ogupdate['parent2commission'] > 0) {
										$ogupdate['parent3commission'] = $ogupdate['parent3commission'] + $ogupdate['parent2commission'] * $agleveldata3['commission_parent_pj'] * 0.01;
									}
								}
							}
							//持续推荐奖励
							if($agleveldata4['commission_parent'] > 0) {
								if($agleveldata3['commissiontype']==1){
									$ogupdate['parent4commission'] = $agleveldata4['commission_parent'];
								} else {
									$ogupdate['parent4commission'] = $ogupdate['parent3commission'] * $agleveldata4['commission_parent'] * 0.01;
								}
							}
							if($agleveldata3['id'] == $agleveldata4['id'] && $agleveldata4['commission_parent_pj'] > 0) {
								if($agleveldata3['commissiontype']==1){
									$ogupdate['parent4commission'] = $agleveldata4['commission_parent_pj'];
								} else {
									$ogupdate['parent4commission'] = $ogupdate['parent3commission'] * $agleveldata4['commission_parent_pj'] * 0.01;
								}
							}
						}
					}
					if($ogupdate){
						Db::name('shop_order_goods')->where('id',$ogid)->update($ogupdate);
					}

					if($product['commissionset4']==1 && $product['lvprice']==1){ //极差分销
						if($member['path']){
							$parentList = Db::name('member')->where('id','in',$member['path'])->order(Db::raw('field(id,'.$member['path'].')'))->select()->toArray();
							if($parentList){
								$parentList = array_reverse($parentList);
								$lvprice_data = json_decode($guige['lvprice_data'],true);
								$nowprice = $commission_totalpriceCache;
								$giveidx = 0;
								foreach($parentList as $k=>$parent){
									if($parent['levelid'] && $lvprice_data[$parent['levelid']]){
										$thisprice = floatval($lvprice_data[$parent['levelid']]) * $num;
										if($nowprice > $thisprice){
											$commission = $nowprice - $thisprice;
											$nowprice = $thisprice;
											$giveidx++;
											//if($giveidx <=3){
											//	$ogupdate['parent'.$giveidx] = $parent['id'];
											//	$ogupdate['parent'.$giveidx.'commission'] = $commission;
											//}
											Db::name('member_commission_record')->insert(['aid'=>aid,'mid'=>$parent['id'],'frommid'=>$mid,'orderid'=>$orderid,'ogid'=>$ogid,'type'=>'shop','commission'=>$commission,'score'=>0,'remark'=>'下级购买商品差价','createtime'=>time()]);
										}
									}
								}
							}
						}
					}

					if($product['commissionset']!=4){
						if(false){}else{
							if($ogupdate['parent1'] && ($ogupdate['parent1commission'] || $ogupdate['parent1score'])){
								Db::name('member_commission_record')->insert(['aid'=>aid,'mid'=>$ogupdate['parent1'],'frommid'=>$mid,'orderid'=>$orderid,'ogid'=>$ogid,'type'=>'shop','commission'=>$ogupdate['parent1commission'],'score'=>$ogupdate['parent1score'],'remark'=>'下级购买商品奖励','createtime'=>time()]);
							}
							if($ogupdate['parent2'] && ($ogupdate['parent2commission'] || $ogupdate['parent2score'])){
								Db::name('member_commission_record')->insert(['aid'=>aid,'mid'=>$ogupdate['parent2'],'frommid'=>$mid,'orderid'=>$orderid,'ogid'=>$ogid,'type'=>'shop','commission'=>$ogupdate['parent2commission'],'score'=>$ogupdate['parent2score'],'remark'=>'下二级购买商品奖励','createtime'=>time()]);
							}
							if($ogupdate['parent3'] && ($ogupdate['parent3commission'] || $ogupdate['parent3score'])){
								Db::name('member_commission_record')->insert(['aid'=>aid,'mid'=>$ogupdate['parent3'],'frommid'=>$mid,'orderid'=>$orderid,'ogid'=>$ogid,'type'=>'shop','commission'=>$ogupdate['parent3commission'],'score'=>$ogupdate['parent3score'],'remark'=>'下三级购买商品奖励','createtime'=>time()]);
							}
							if($ogupdate['parent4'] && ($ogupdate['parent4commission'])){
								Db::name('member_commission_record')->insert(['aid'=>aid,'mid'=>$ogupdate['parent4'],'frommid'=>$mid,'orderid'=>$orderid,'ogid'=>$ogid,'type'=>'shop','commission'=>$ogupdate['parent4commission'],'score'=>0,'remark'=>'持续推荐奖励','createtime'=>time()]);
							}
						}
					}
				}
			}
			if($info['status'] == 0){
				$newordernum = date('ymdHis').rand(100000,999999);
				$ordernumArr = explode('_',$info['ordernum']);
				if($ordernumArr[1]) $newordernum .= '_'.$ordernumArr[1];
				Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->update(['ordernum'=>$newordernum]);
				Db::name('shop_order_goods')->where('aid',aid)->where('orderid',$orderid)->update(['ordernum'=>$newordernum]);
				
				$payorderid = Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->value('payorderid');
				\app\model\Payorder::updateorder($payorderid,$newordernum,$postinfo['totalprice'],$orderid);
			}
			\app\common\System::plog('商城订单编辑'.$orderid);
			return json(['status'=>1,'msg'=>'修改成功']);
		}
		View::assign('info',$info);
		View::assign('order_goods',$order_goods);
		View::assign('discount',$discount);
		View::assign('express_data',express_data());
		return View::fetch();
	}
	//送货单
	public function shd(){
		$orderid = input('param.id/d');
		$info = Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->find();
		if(!$info || (bid !=0 && $info['bid'] != bid)) showmsg('订单不存在');
		$order_goods = Db::name('shop_order_goods')->where('aid',aid)->where('orderid',$orderid)->select()->toArray();

		$totalnum = 0;
		foreach($order_goods as $k=>$v){
			$order_goods[$k]['lvprice'] = Db::name('shop_product')->where('id',$v['proid'])->value('lvprice'); //是否开启会员价
            $remark = '';
            $order_goods[$k]['remark'] = $info['message'].($remark?'，'.$remark:'');
            $totalnum += $v['num'];
		}
		$member = Db::name('member')->where('id',$info['mid'])->find();
		$userlevel = Db::name('member_level')->where('aid',aid)->where('id',$member['levelid'])->find();
		if($userlevel && $userlevel['discount']>0 && $userlevel['discount']<10){
			$discount = $userlevel['discount']*0.1; //会员折扣
		}else{
			$discount = 1;
		}
		$order_goods2 = [];
		if(count($order_goods) < 10){
    		for($i=0;$i<10;$i++){
    			$order_goods2[] = $order_goods[$i];
    		}
		}else{
		    $order_goods2 = $order_goods;
		}
		if(!getcustom('baikangxie')){
			$order_goods2[] = ['type'=>'yf'];
			$order_goods2[] = ['type'=>'totalprice'];
			$order_goods2[] = ['type'=>'totalprice2'];
		}else{
			$order_goods2[] = ['name'=>'合计','num'=>$totalnum];
		}
		$order_goods3 = array_chunk($order_goods2,13);


		$info['totalprice2'] = num_to_rmb($info['totalprice']);
		if($info['freight_type'] == 11){
			$info['freight_content'] = json_decode($info['freight_content'],true);
		}
		if($info['bid'] == 0){
			$bname = Db::name('admin_set')->where('aid',0)->value('name');
		}else{
			$bname = Db::name('business')->where('id',$info['bid'])->value('name');
		}



        $shipping_pagetitle = Db::name('shop_sysset')->where('aid',aid)->value('shipping_pagetitle');
		View::assign('bname',$bname);
        View::assign('shipping_pagetitle',$shipping_pagetitle);
		View::assign('info',$info);
		View::assign('order_goods3',$order_goods3);
		View::assign('discount',$discount);
		View::assign('express_data',express_data());
		return View::fetch();
	}


	//批量打印送货单
	public function plshd(){
		$orderids = input('param.ids');
		$orderarr = explode(',',$orderids);
		$goodslist = [];
		foreach($orderarr as $k=>$orderid){
			$info = Db::name('shop_order')->where('aid',aid)->where('id',$orderid)->find();
			if(!$info || (bid !=0 && $info['bid'] != bid)) showmsg('订单不存在');
			$order_goods = Db::name('shop_order_goods')->where('aid',aid)->where('orderid',$orderid)->select()->toArray();

			$totalnum = 0;
			foreach($order_goods as $k=>$v){
				$order_goods[$k]['lvprice'] = Db::name('shop_product')->where('id',$v['proid'])->value('lvprice'); //是否开启会员价
				$totalnum += $v['num'];
			}
			$member = Db::name('member')->where('id',$info['mid'])->find();
			$userlevel = Db::name('member_level')->where('aid',aid)->where('id',$member['levelid'])->find();
			if($userlevel && $userlevel['discount']>0 && $userlevel['discount']<10){
				$discount = $userlevel['discount']*0.1; //会员折扣
			}else{
				$discount = 1;
			}
			$order_goods2 = [];
			if(count($order_goods) < 10){
				for($i=0;$i<10;$i++){
					$order_goods2[] = $order_goods[$i];
				}
			}else{
				$order_goods2 = $order_goods;
			}
			if(!getcustom('baikangxie')){
				$order_goods2[] = ['type'=>'yf'];
				$order_goods2[] = ['type'=>'totalprice'];
				$order_goods2[] = ['type'=>'totalprice2'];
			}else{
				$order_goods2[] = ['name'=>'合计','num'=>$totalnum];
			}
			$order_goods3 = array_chunk($order_goods2,13);


			$info['totalprice2'] = num_to_rmb($info['totalprice']);
			if($info['freight_type'] == 11){
				$info['freight_content'] = json_decode($info['freight_content'],true);
			}
			if($info['bid'] == 0){
				$bname = Db::name('admin_set')->where('aid',0)->value('name');
			}else{
				$bname = Db::name('business')->where('id',$info['bid'])->value('name');
			}
			$info['order_goods3'] = $order_goods3;
			$goodslist[] = $info;
			
		}
	
        $shipping_pagetitle = Db::name('shop_sysset')->where('aid',aid)->value('shipping_pagetitle');
		View::assign('bname',$bname);
        View::assign('shipping_pagetitle',$shipping_pagetitle);
		View::assign('goodslist',$goodslist);
		View::assign('count',count($goodslist));
		View::assign('discount',$discount);
		View::assign('express_data',express_data());
		return View::fetch();
	}



	//订单统计
	public function tongji(){
		if(request()->isAjax() || input('param.excel') == 1){
			if(input('param.type')==3){
				$year = date('Y');
				$month = '';
				$day = '';
				$tjtype = 1;
				if(input('param.year')) $year = input('param.year');
				if(input('param.month')) $month = input('param.month');
				if(input('param.day')) $day = input('param.day');
				if(input('param.tjtype')) $tjtype = input('param.tjtype');

				$data = [];
				$totalval = 0;
				$maxval = 0;
				$maxdate = '';
				if(!$month){
					for($i=1;$i<13;$i++){
						$thismonth = $i >=10 ? ''.$i : '0'.$i;
						$starttime = strtotime($year.'-'.$thismonth.'-01');
						if($thismonth == 12){
							$endtime = strtotime(($year+1).'-01-01');
						}else{
							$nextmonth = $thismonth+1;
							$nextmonth = $nextmonth >=10 ? ''.$nextmonth : '0'.$nextmonth;
							$endtime = strtotime($year.'-'.$nextmonth.'-01');
						}
						
						$thisdata = [];
						$thisdata['date'] = $i;
						if($tjtype == 1){ //成交额
							if(bid == 0){
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->sum('totalprice');
							}else{
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->sum('totalprice');
							}
						}else{ //成交量
							if(bid == 0){
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->count();
							}else{
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->count();
							}
						}
						$val = round($val,2);
						$totalval += $val;
						$thisdata['val'] = $val;
						
						if($maxval < $val){
							$maxval = $val;
							$maxdate = $thismonth.'月';
						}
						$data[] = $thisdata;
					}
					$title = array('月份',$tjtype == 1 ? '交易额' : '交易量','占比');
				}elseif(!$day){
					$month = $month>9?''.$month:'0'.$month;
					$ts = date('t',strtotime($year.'-'.$month.'-01'));
					for($i=1;$i<$ts;$i++){
						$thisday = $i >=10 ? ''.$i : '0'.$i;
						$starttime = strtotime($year.'-'.$month.'-'.$thisday);
						$endtime = $starttime + 86400;
						
						$thisdata = [];
						$thisdata['date'] = $i;
						if($tjtype == 1){ //成交额
							if(bid == 0){
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->sum('totalprice');
							}else{
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->sum('totalprice');
							}
						}else{ //成交量
							if(bid == 0){
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->count();
							}else{
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->count();
							}
						}
						$val = round($val,2);
						$totalval += $val;
						$thisdata['val'] = $val;

						if($maxval < $val){
							$maxval = $val;
							$maxdate = $thisday.'日';
						}
						$data[] = $thisdata;
					}
					$title = array('日期',$tjtype == 1 ? '交易额' : '交易量','占比');
				}else{
					$month = $month>9?''.$month:'0'.$month;
					$day = $day >6 ? ''.$day : '0'.$day;
					for($i=0;$i<24;$i++){
						$starttime = strtotime($year.'-'.$month.'-'.$day) + $i*3600;
						$endtime = $starttime + 3600;
						
						$thisdata = [];
						$thisdata['date'] = $i.'点-'.($i+1).'点';
						if($tjtype == 1){ //成交额
							if(bid == 0){
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->sum('totalprice');
							}else{
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->sum('totalprice');
							}
						}else{ //成交量
							if(bid == 0){
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->count();
							}else{
								$val = 0 + Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('paytime','>=',$starttime)->where('paytime','<',$endtime)->where('status','in','1,2,3')->count();
							}
						}
						$val = round($val,2);
						$totalval += $val;
						$thisdata['val'] = $val;

						if($maxval < $val){
							$maxval = $val;
							$maxdate =$i.'点-'.($i+1).'点';
						}
						$data[] = $thisdata;
					}
					$title = array('时间',$tjtype == 1 ? '交易额' : '交易量','占比');
				}
				$totalval = round($totalval,2);
				foreach($data as $k=>$v){
					if($totalval == 0){
						$data[$k]['percent'] = 0;
					}else{
						$data[$k]['percent'] = round($v['val'] / $totalval * 100,2);
					}
				}

				if(input('param.excel') == 1){
					$data[] = ['date'=>'总数','val'=>$totalval,'percent'=>''];
					$data[] = ['date'=>'最高','val'=>$maxval,'percent'=>''];
					$this->export_excel($title,$data);
				}
				return json(['code'=>0,'msg'=>'查询成功','count'=>count($data),'data'=>$data,'tjtype'=>$tjtype,'totalval'=>$totalval,'maxval'=>$maxval,'maxdate'=>$maxdate]);
			}elseif(input('param.type')==5){
				if(input('param.excel') == 1){
					$page = 1;
					$limit = 10000000;
				}else{
					$page = input('param.page');
					$limit = input('param.limit');
				}
				if(input('param.field') && input('param.order')){
					$order = input('param.field').' '.input('param.order');
				}else{
					$order = 'sort desc,id desc';
				}
				$where = array();
				$where[] = ['aid','=',aid];
				$where[] = ['bid','=',bid];
				if(input('param.name')) $where[] = ['name','like','%'.$_GET['name'].'%'];
				$count = 0 + Db::name('shop_product')->where($where)->count();
				$data = Db::name('shop_product')->field('*,(select sum(num) from ddwx_shop_order_goods where proid=ddwx_shop_product.id and status in(1,2,3)) buynum,((select sum(num) from ddwx_shop_order_goods where proid=ddwx_shop_product.id and status in(1,2,3)) / viewnum) buypercent')->where($where)->page($page,$limit)->order($order)->select()->toArray();

				$exceldata = [];
				foreach($data as $k=>$v){
					//$data[$k]['buynum'] = Db::name('shop_order_goods')->where('aid',aid)->where('proid',$v['id'])->where('status','in','1,2,3')->sum('num');
					if(!$v['buynum']){
						$data[$k]['buynum'] = 0;
					}
					$data[$k]['buypercent'] = $v['viewnum'] > 0 ? round( $v['buynum'] / $v['viewnum'] * 100 ,2) : 0;
					$exceldata[] = [$v['name'],$v['viewnum'],$data[$k]['buynum'],$data[$k]['buypercent'].'%'];
				}
				if(input('param.excel') == 1){
					$title = ['商品名称','访问次数','购买件数','转化率'];
					$this->export_excel($title,$exceldata);
				}

				return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data]);
			}else{
				$page = input('param.page');
				$limit = input('param.limit');
				if(input('param.field') && input('param.order')){
					$order = input('param.field').' '.input('param.order');
				}else{
					$order = 'totalprice desc';
				}
				$where = [];
				$where[] = ['og.aid','=',aid];
				$where[] = ['og.bid','=',bid];
				$where[] = ['og.status','in','1,2,3'];
				if($this->mdid){
					$where[] = ['mdid','=',$this->mdid];
				}
				if(input('param.ctime') ){
					$ctime = explode(' ~ ',input('param.ctime'));
					$where[] = ['og.createtime','>=',strtotime($ctime[0])];
					$where[] = ['og.createtime','<',strtotime($ctime[1]) + 86400];
				}
				if(input('param.paytime') ){
					$ctime = explode(' ~ ',input('param.paytime'));
					$where[] = ['shop_order.paytime','>=',strtotime($ctime[0])];
					$where[] = ['shop_order.paytime','<',strtotime($ctime[1]) + 86400];
				}
				if(input('param.proname')){
					$where[] = ['og.name','like','%'.input('param.proname').'%'];
				}
				if(input('param.cid') && input('param.cid')!==''){
					//取出cid 在的商品
					$cid = input('param.cid');
					//子分类
					$clist = Db::name('shop_category')->where('aid',aid)->where('pid',$cid)->column('id');
					if($clist){
						$clist2 = Db::name('shop_category')->where('aid',aid)->where('pid','in',$clist)->column('id');
						$cCate = array_merge($clist, $clist2, [$cid]);
						if($cCate){
							$whereCid = [];
							foreach($cCate as $k => $c2){
								$whereCid[] = "find_in_set({$c2},cid)";
							}
							$where[] = Db::raw(implode(' or ',$whereCid));
						}
					} else {
						$where[] = Db::raw("find_in_set(".$cid.",cid)");
					}
					

					//$cprolist = Db::name('shop_product')->where('aid',aid)->where("find_in_set(".input('param.cid').",cid)")->column('id');
					//var_dump($cprolist);
					//if($cprolist){
					//	$where[] =  ['og.proid','in',$cprolist];
					//}
				}
				$fields = 'og.proid,og.name,og.pic,og.ggname,sum(og.num) num,sum(og.totalprice) totalprice,sum(og.totalprice)/sum(og.num) as avgprice,sum(og.cost_price*og.num) as chengben,sum(og.totalprice-og.cost_price*og.num) lirun';
				if(input('param.type')==2){
					$count = 0 + Db::name('shop_order_goods')->alias('og')->join('shop_order','shop_order.id=og.orderid')->fieldRaw('og.proid')->where($where)->group('ggid')->count();
					$list = Db::name('shop_order_goods')->alias('og')->join('shop_order','shop_order.id=og.orderid')->fieldRaw($fields)->where($where)->group('ggid')->page($page,$limit)->order($order)->select()->toArray();
				}elseif(input('param.type')==7){
                    }else{
					$count = 0 + Db::name('shop_order_goods')->alias('og')->join('shop_order','shop_order.id=og.orderid')->fieldRaw('og.proid')->where($where)->group('proid')->count();
					$list = Db::name('shop_order_goods')->alias('og')->join('shop_order','shop_order.id=og.orderid')->fieldRaw($fields)->where($where)->group('proid')->page($page,$limit)->order($order)->select()->toArray();
					//var_dump(db('shop_order_goods')->getlastsql());
				}

				foreach($list as $k=>$v){
					$list[$k]['ph'] = ($k+1) + ($page-1)*$limit;
					$list[$k]['avgprice'] = number_format($v['avgprice'],2,'.','');
					}
				return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$list]);
			}
		}
		if(input('param.type')==3){
			return View::fetch('tongji3');
		}
		if(input('param.type')==4){
			$membercount = Db::name('member')->where('aid',aid)->count(); //总会员数
			if(bid == 0){
				$totalprice = Db::name('shop_order')->where('aid',aid)->where('status','in','1,2,3')->sum('totalprice'); //总订单金额
				$totalnum = Db::name('shop_order')->where('aid',aid)->where('status','in','1,2,3')->count(); //总订单数
				$totalview = Db::name('shop_product')->where('aid',aid)->sum('viewnum'); //总访问数
				$memberxf = Db::name('shop_order')->where('aid',aid)->group('mid')->where('status','in','1,2,3')->count(); //消费会员数
			}else{
				$totalprice = Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('status','in','1,2,3')->sum('totalprice'); //总订单金额
				$totalnum = Db::name('shop_order')->where('aid',aid)->where('bid',bid)->where('status','in','1,2,3')->count(); //总订单数
				$totalview = Db::name('shop_product')->where('aid',aid)->where('bid',bid)->sum('viewnum'); //总访问数
				$memberxf = Db::name('shop_order')->where('aid',aid)->where('bid',bid)->group('mid')->where('status','in','1,2,3')->count(); //消费会员数
			}

			$percent1 = $membercount > 0 ? round($totalprice / $membercount,2) : 0; //会员人均消费
			$percent2 = $totalview > 0 ? round($totalprice / $totalview * 100,2) : 0; //访问转换率
			$percent3 = $totalview > 0 ? round($totalnum / $totalview * 100,2) : 0; //订单转化率
			$percent4 = $membercount > 0 ? round($memberxf / $membercount * 100,2) : 0; //会员消费率
			$percent5 = $membercount > 0 ? round($totalnum / $membercount * 100,2) : 0; //订单购买率

			View::assign('membercount',$membercount);
			View::assign('totalprice',round($totalprice,2));
			View::assign('totalnum',$totalnum);
			View::assign('totalview',$totalview);
			View::assign('memberxf',$memberxf);
			View::assign('percent1',$percent1);
			View::assign('percent2',$percent2);
			View::assign('percent3',$percent3);
			View::assign('percent4',$percent4);
			View::assign('percent5',$percent5);
			return View::fetch('tongji4');
		}
		if(input('param.type')==5){
			return View::fetch('tongji5');
		}
		if(input('param.type')==6){
			//取出商城分类
			$catelist =  Db::name('shop_category')->where('aid',aid)->where('pid','=',0)->select()->toArray();
			View::assign('paytime',input('param.paytime'));
			View::assign('catelist',$catelist);
			return View::fetch('tongji6');
		}
		//是不是有学校班级统计
        return View::fetch();
	}
	//导出
	public function tjexcel(){
		set_time_limit(0);
		ini_set('memory_limit', '2000M');
		if(input('param.field') && input('param.order')){
			$order = input('param.field').' '.input('param.order');
		}else{
			$order = 'totalprice desc';
		}
		$where = [];
		$where[] = ['og.aid','=',aid];
		$where[] = ['og.bid','=',bid];
		$where[] = ['og.status','in','1,2,3'];
		if($this->mdid){
			$where[] = ['mdid','=',$this->mdid];
		}
		if(input('param.ctime') ){
			$ctime = explode(' ~ ',input('param.ctime'));
			$where[] = ['og.createtime','>=',strtotime($ctime[0])];
			$where[] = ['og.createtime','<',strtotime($ctime[1]) + 86400];
		}
		if(input('param.paytime') ){
			$ctime = explode(' ~ ',input('param.paytime'));
			$where[] = ['shop_order.paytime','>=',strtotime($ctime[0])];
			$where[] = ['shop_order.paytime','<',strtotime($ctime[1]) + 86400];
		}
		if(input('param.proname')){
			$where[] = ['og.name','like','%'.input('param.proname').'%'];
		}
		if(input('param.cid')){
			$where[] = ['og.cid','=',input('param.cid')];
		}
		$fields = 'og.proid,og.name,og.pic,og.ggname,sum(og.num) num,sum(og.totalprice) totalprice,sum(og.totalprice)/sum(og.num) as avgprice';
		if(input('param.type')==2){
			$list = Db::name('shop_order_goods')->alias('og')->join('shop_order','shop_order.id=og.orderid')->field($fields)->where($where)->group('ggid')->order($order)->select()->toArray();
		}elseif(input('param.type')==7){
            }else{
			$list = Db::name('shop_order_goods')->alias('og')->join('shop_order','shop_order.id=og.orderid')->field($fields)->where($where)->group('proid')->order($order)->select()->toArray();
		}
		foreach($list as $k=>$v){
			$list[$k]['ph'] = ($k+1);
			$list[$k]['avgprice'] = number_format($v['avgprice'],2,'.','');
		}
		if(input('param.type')==2){
			$title = array('排名','商品名称','商品规格','销售数量','销售金额','平均单价');
			$data = [];
			foreach($list as $k=>$vo){
				$data[] = [
					$vo['ph'],
					$vo['name'],
					$vo['ggname'],
					$vo['num'],
					$vo['totalprice'],
					$vo['avgprice'],
				];

			}
		}elseif(input('param.type')==7){
            }else{
			$title = array('排名','商品名称','销售数量','销售金额','平均单价');
			$data = [];
			foreach($list as $k=>$vo){
				$data[] = [
					$vo['ph'],
					$vo['name'],
					$vo['num'],
					$vo['totalprice'],
					$vo['avgprice'],
				]; 
			}
		}
		$this->export_excel($title,$data);
	}

	
	private function excel2($list){
		$title = array('订单号','客户名称','业务员','业务员手机号码','产品代码','产品条码','商品名称','规格','数量','单价','总价','已付金额','支付方式','收货信息','配送方式','备注','其他');
		$data = [];
		foreach($list as $k=>$vo){
			$member = Db::name('member')->where('id',$vo['mid'])->find();
			$oglist = Db::name('shop_order_goods')->where('orderid',$vo['id'])->select()->toArray();
			$invoice = Db::name('invoice')->where('aid',aid)->where('order_type','shop')->where('orderid',$vo['id'])->find();
			if($vo['bid'] != 0){
				$business = Db::name('business')->where('id',$vo['bid'])->find();
			}else{
				$business = [];
				if($member['levelid']!=3){
					if($member['realname']) $business['linkman'] = $member['realname'];
					if($member['tel']) $business['linktel'] = $member['tel'];
				}
			}
			$xm=array();
			foreach($oglist as $og){
				$xm[] = $og['name']."/".$og['ggname']." × ".$og['num']."";
				$status='';
				if($vo['status']==0){
					$status = '未支付';
				}elseif($vo['status']==2){
					$status = '已发货';
				}elseif($vo['status']==1){
					$status = '已支付';
				}elseif($vo['status']==3){
					$status = '已收货';
				}elseif($vo['status']==4){
					$status = '已关闭';
				}
				$remark = '';
				if($vo['freight_time']) $remark.= $vo['freight_time']."\r\n";
				/*
				if($invoice){
					if($remark) $remark .= "\r\n";
					if($invoice['type'] == 1){
						$remark.= $invoice['invoice_name'].' '.$invoice['mobile'].' '.$invoice['emall'];
					}else{
						if($invoice['name_type'] == 1){
							$remark.= $invoice['invoice_name'].' '.$invoice['tax_no'].' '.$invoice['mobile'].' '.$invoice['emall'];
						}else{
							$remark.= $invoice['invoice_name'].' '.$invoice['tax_no'].' '.$invoice['address'].' '.$invoice['tel'].' '.$invoice['bank_name'].' '.$invoice['bank_account'];
						}
					}
				}
				*/
                //配送自定义表单
                $vo['formdata'] = \app\model\Freight::getformdata($vo['id'],'shop_order');
                if($vo['formdata']) {
                    foreach ($vo['formdata'] as $formdata) {
                        if($formdata[2] != 'upload') {
                            $remark .= $formdata[0].':'.$formdata[1]."\r\n";
                        }
                    }
                }
				$data[] = [
					' '.$vo['ordernum'],
					$invoice ? $invoice['invoice_name'] : '',
					$business['linkman'],
					$business['linktel'],
					$og['procode'],
                    $og['barcode'],
					$og['name'],
					$og['ggname'],
					$og['num'],
					$og['sell_price'],
					$og['totalprice'],
					in_array($vo['status'],[1,2,3]) ? $og['totalprice'] : 0,
					$vo['paytype'],
					$vo['area'].' '.$vo['address'] . ','.$vo['linkman']. ','.$vo['company'].','.$vo['tel'],
					$vo['freight_text'],
					$remark
				];
			}
		}
		$this->export_excel($title,$data);
	}


	//订单统计
    public function tongjiAdminuser(){
        if(request()->isAjax()){
            $page = input('param.page');
            $limit = input('param.limit');
            if(input('param.field') && input('param.order')){
                $order = input('param.field').' '.input('param.order');
            }else{
                $order = 'id';
            }
            $where = array();
            $where[] = ['aid','=',aid];
            $where[] = ['bid','=',bid];
            if(input('param.un')) $where[] = ['un','like','%'.input('param.un').'%'];
            if($this->user['isadmin'] == 0){
                if($this->user['groupid'] == 0){
                    $where[] = ['addid','=',$this->user['id']];
                }else{
                    $thisgroup = Db::name('admin_user_group')->where('id',$this->user['groupid'])->find();
                    $groupids = Db::name('admin_user_group')->where('aid',aid)->where('bid',bid)->where("`sort`<".$thisgroup['sort']." or (`sort`={$thisgroup['sort']} and id>{$thisgroup['id']})")->column('id');
                    if($groupids){
                        $where[] = ['groupid','in',$groupids];
                    }else{
                        $where[] = Db::raw('1=0');
                    }
                }
            }
            $count = 0 + Db::name('admin_user')->where($where)->whereOr('id','=',$this->user['id'])->whereOr("groupid=0 and addid=".$this->user['id'])->count();
            $data = Db::name('admin_user')->where($where)->whereOr('id','=',$this->user['id'])->whereOr("groupid=0 and addid=".$this->user['id'])->page($page,$limit)->order($order)->select()->toArray();
            foreach($data as $k=>$v){
                $data[$k]['total'] = 0;
                if($v['mid']){
                    $member = Db::name('member')->where('aid',aid)->where('id',$v['mid'])->find();
                    if($member){
                        $data[$k]['headimg'] = $member['headimg'];
                        $data[$k]['nickname'] = $member['nickname'];
                    }
                    $childrenmid = \app\common\Member::getdownmids(aid,$v['mid']);
                    $data[$k]['total'] = $this->orderSumByMids($childrenmid);
                }
            }
            return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data]);
        }
        return View::fetch();
    }
    //导出
    public function tongjiadminExcel(){
        set_time_limit(0);
        ini_set('memory_limit', '2000M');
        $where = array();
        $where[] = ['aid','=',aid];
        $where[] = ['bid','=',bid];
        if(input('param.un')) $where[] = ['un','like','%'.input('param.un').'%'];
        if($this->user['isadmin'] == 0){
            if($this->user['groupid'] == 0){
                $where[] = ['addid','=',$this->user['id']];
            }else{
                $thisgroup = Db::name('admin_user_group')->where('id',$this->user['groupid'])->find();
                $groupids = Db::name('admin_user_group')->where('aid',aid)->where('bid',bid)->where("`sort`<".$thisgroup['sort']." or (`sort`={$thisgroup['sort']} and id>{$thisgroup['id']})")->column('id');
                if($groupids){
                    $where[] = ['groupid','in',$groupids];
                }else{
                    $where[] = Db::raw('1=0');
                }
            }
        }
        $data = Db::name('admin_user')->where($where)->whereOr('id','=',$this->user['id'])->whereOr("groupid=0 and addid=".$this->user['id'])->order($order)->select()->toArray();
        foreach($data as $k=>$v){
            $data[$k]['total'] = 0;
            if($v['mid']){
                $member = Db::name('member')->where('aid',aid)->where('id',$v['mid'])->find();
                if($member){
                    $data[$k]['headimg'] = $member['headimg'];
                    $data[$k]['nickname'] = $member['nickname'];
                }
                $childrenmid = \app\common\Member::getdownmids(aid,$v['mid']);
                $data[$k]['total'] = $this->orderSumByMids($childrenmid);
            }
        }
        $list= $data;
        $title = array('ID','账号','业绩','会员信息');
        $data = [];
        foreach($list as $k=>$vo){
            $data[] = [
                $vo['id'],
                $vo['un'],
                $vo['total'],
                $vo['nickname'].'('.$vo['mid'].')'
            ];
        }
        $this->export_excel($title,$data);
    }

    private function orderSumByMids($mids){
        if(empty($mids)) return 0;

        $where = [];
        $where[] = ['aid','=',aid];
        $where[] = ['bid','=',bid];
        $where[] = ['status','in','1,2,3'];
        $where[] = ['mid','in',$mids];
        if($this->mdid){
            $where[] = ['mdid','=',$this->mdid];
        }
        if(input('param.ctime') ){
            $ctime = explode(' ~ ',input('param.ctime'));
            $where[] = ['createtime','>=',strtotime($ctime[0])];
            $where[] = ['createtime','<',strtotime($ctime[1]) + 86400];
        }
        if(input('param.paytime') ){
            $ctime = explode(' ~ ',input('param.paytime'));
            $where[] = ['paytime','>=',strtotime($ctime[0])];
            $where[] = ['paytime','<',strtotime($ctime[1]) + 86400];
        }
        $totalprice = 0 + Db::name('shop_order')->where($where)->sum('totalprice');
        $totalprice = round($totalprice,2);
        return $totalprice;

    }

	public function getordercount(){
		$ctime = input('param.ctime');
		if(!$ctime){
			return json(['ordercount'=>0,'orderprice'=>0]);
		}
		$ctime = explode(' ~ ',input('param.ctime'));
		
		$sysset = Db::name('admin_set')->where('aid',aid)->find();
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['status','=',3];
		$where[] = ['endtime','>=',strtotime($ctime[0])];
		$where[] = ['endtime','<',strtotime($ctime[1]) + 86400];
		$where[] = ['isfenhong','=',0];
		//多商户的商品是否参与分红
		if($sysset['fhjiesuanbusiness'] != 1){
			$where[] = ['bid','=',0];
		}
		$ordercount = Db::name('shop_order_goods')->where($where)->group('orderid')->count();
		$orderprice = Db::name('shop_order_goods')->where($where)->sum('real_totalprice');
		return json(['ordercount'=>$ordercount,'orderprice'=>round($orderprice,2)]);
	}
	public function fhjiesuan(){
		$ctime = input('param.ctime');
		if(!$ctime){
			return json(['status'=>0,'msg'=>'请选择时间范围']);
		}
		$ctime = explode(' ~ ',input('param.ctime'));
		$starttime = strtotime($ctime[0]);
		$endtime = strtotime($ctime[1]) + 86400;
		\app\common\Fenhong::jiesuan(aid,$starttime,$endtime);
		return json(['status'=>1,'msg'=>'结算完成']);
	}
	//转账审核
    public function transferCheck(){
        }
}
